阿里云主机折上折
  • 微信号
Current Site:Index > Function Basics

Function Basics

Author:Chuan Chen 阅读数:24485人阅读 分类: JavaScript

In programming, functions are the core units for organizing code, enabling logic encapsulation, code reuse, and improved maintainability. JavaScript functions are highly flexible, supporting multiple definition and invocation methods. Understanding their fundamental concepts is key to mastering the language.

Function Definition and Declaration

In JavaScript, functions can be defined using function declarations or function expressions. Function declarations are hoisted, allowing them to be called before definition, whereas function expressions are not.

// Function declaration
function greet(name) {
  return `Hello, ${name}!`;
}

// Function expression
const greet = function(name) {
  return `Hello, ${name}!`;
};

Arrow functions, introduced in ES6, provide a concise syntax ideal for anonymous scenarios:

const greet = (name) => `Hello, ${name}!`;

Parameters and Return Values

Function parameters support default values, which can be specified directly in the parameter list since ES6:

function createUser(name, role = 'user') {
  return { name, role };
}
console.log(createUser('Alice')); // { name: 'Alice', role: 'user' }

Return values are passed via return. If no explicit return is provided, the function defaults to returning undefined:

function noReturn() {}
console.log(noReturn()); // undefined

Scope and Closures

Function scope limits the accessibility of variables. Closures allow functions to access variables outside their lexical scope:

function outer() {
  let count = 0;
  return function inner() {
    count++;
    return count;
  };
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2

Higher-Order Functions

Functions that accept or return other functions are called higher-order functions, commonly seen in array methods:

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2); // [2, 4, 6]

Immediately Invoked Function Expressions (IIFE)

IIFEs execute immediately upon definition and are used to create isolated scopes:

(function() {
  console.log('Executed immediately');
})();

Recursive Functions

Functions that call themselves are called recursive functions, requiring careful attention to termination conditions:

function factorial(n) {
  if (n === 1) return 1;
  return n * factorial(n - 1);
}
console.log(factorial(5)); // 120

Function Methods and Properties

Functions, as objects, have methods like call, apply, and bind:

function showInfo(age, city) {
  console.log(`${this.name}, ${age}, ${city}`);
}

const user = { name: 'Bob' };
showInfo.call(user, 30, 'New York'); // Bob, 30, New York

Asynchronous Functions

ES2017 introduced async/await to simplify asynchronous operations:

async function fetchData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:定时器与延时器

下一篇:作用域与闭包

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.