functions and variables javascript

Functions and Variables in JavaScript

JavaScript is a versatile language that allows developers to create complex web applications. Two essential concepts in JavaScript are functions and variables.

Variables

Variables are used to store values in JavaScript. They are like containers that can hold any type of data such as numbers, strings, or boolean values. In JavaScript, we can declare variables using the var, let, or const keyword.

var is the old way of declaring variables in JavaScript. It has some peculiar scoping rules that can lead to unexpected behavior.

let and const are new ways of declaring variables that were introduced in ECMAScript 2015. They have block scoping, which means they are only accessible within the block they were declared in.


// Variable declaration using var
var myName = "Raju";

// Variable declaration using let
let myAge = 26;

// Variable declaration using const
const PI = 3.14159;

Functions

Functions are reusable blocks of code that perform a specific task. They make it easier to write modular and maintainable code. In JavaScript, we can define functions using the function keyword.


// Function declaration
function greet(name) {
  console.log("Hello " + name);
}

// Function call
greet("Raju"); // Output: "Hello Raju"

Functions can also return values using the return keyword. The returned value can be stored in a variable or used directly in code.


// Function that returns the sum of two numbers
function add(a, b) {
  return a + b;
}

// Using the returned value
let result = add(2, 3); // Result: 5

JavaScript also supports anonymous functions, which are functions without a name. They can be assigned to a variable or used directly in code.


// Anonymous function assigned to a variable
let sayHello = function(name) {
  console.log("Hello " + name);
};

// Using the anonymous function
sayHello("Raju"); // Output: "Hello Raju"

Arrow functions are another way to define functions in JavaScript. They provide a concise syntax for writing functions that take one or more arguments and return a value.


// Arrow function that returns the sum of two numbers
let add = (a, b) => a + b;

// Using the arrow function
let result = add(2, 3); // Result: 5

Overall, variables and functions are the building blocks of JavaScript. Understanding how they work is crucial for writing efficient and effective code.

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