Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Arrow Function in JavaScript

Js Arrow Function in JavaScript

? JavaScript Arrow Functions


What is an Arrow Function?

  • A concise syntax for writing functions introduced in ES6.

  • Automatically binds the this value to the surrounding context.

  • Ideal for short functions and callbacks.


Basic Syntax

// Traditional functionfunction add(a, b) {  return a + b;}// Arrow functionconst add = (a, b) => {  return a + b;};

More Concise Variants

1. Single Expression — Implicit Return

If the function body is a single expression, you can omit {} and return:

const add = (a, b) => a + b;console.log(add(2, 3));  // 5

2. Single Parameter — Parentheses Optional

const square = x => x * x;console.log(square(4));  // 16

3. No Parameters

const greet = () => console.log("Hello!");greet();  // Hello!

Differences From Regular Functions

  • Arrow functions do not have their own this, arguments, or super.

  • Useful to avoid common this pitfalls in callbacks.

  • Cannot be used as constructors (new keyword).

  • No prototype property.


Examples

const nums = [1, 2, 3];// Using arrow function with forEachnums.forEach(n => console.log(n * 2));  // 2, 4, 6// Arrow function in object method (this refers to outer context)const obj = {  value: 42,  method: () => console.log(this.value)  // 'this' is NOT obj};obj.method();  // undefined (or global this.value)

Want examples showing arrow functions vs regular functions with this?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql