javascript basic function

Javascript Basic Function

As a web developer, it is important to have a good understanding of Javascript. One of the fundamental concepts in Javascript is functions. Functions are reusable blocks of code that perform a specific task.

There are two ways to define functions in Javascript:

  • Function declaration
  • Function expression

Function Declaration

A function declaration is a statement that defines a named function.


function greet(name) {
  console.log(`Hello, ${name}!`);
}

greet("Raju"); // Output: Hello, Raju!

In the example above, we define a function called "greet" that takes one parameter "name". When we call the function with "Raju" as an argument, it prints "Hello, Raju!" to the console.

Function Expression

A function expression is an anonymous function that is assigned to a variable.


const greet = function(name) {
  console.log(`Hello, ${name}!`);
}

greet("Raju"); // Output: Hello, Raju!

In the example above, we define an anonymous function and assign it to a variable called "greet". We then call the function with "Raju" as an argument, and it prints "Hello, Raju!" to the console.

One important thing to note is that function expressions are not hoisted like function declarations. This means that you must define the variable before calling the function.

Arrow Functions

Arrow functions are a shorthand syntax for defining functions in Javascript. They were introduced in ES6.


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

greet("Raju"); // Output: Hello, Raju!

In the example above, we define an arrow function and assign it to a variable called "greet". We then call the function with "Raju" as an argument, and it prints "Hello, Raju!" to the console.

Arrow functions have some differences in behavior compared to regular functions. For example, they do not have their own "this" keyword and cannot be used as constructors. However, they are often more concise and easier to read.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe