JavaScript: A Detailed Guide
JavaScript is a versatile, high-level, and interpreted programming language primarily used for
web development. It allows developers to create interactive and dynamic web pages. JavaScript
is executed on the client side within web browsers but can also be used on the server side with
environments like Node.js.
---
1. Variables in JavaScript
Variables in JavaScript are used to store data values. JavaScript provides three ways to declare
variables:
(i) Using var (Function Scoped)
var is function-scoped, meaning it is accessible within the function where it is declared.
It can be re-declared and updated within the same scope.
If declared outside a function, it becomes a global variable.
Example:
var x = 10;
console.log(x); // Output: 10
(ii) Using let (Block Scoped)
let is block-scoped, meaning it is accessible only within the block {} where it is declared.
It can be updated but cannot be re-declared in the same scope.
Example:
let y = 20;
y = 30; // Allowed
console.log(y); // Output: 30
(iii) Using const (Constant Block Scoped)
const is block-scoped and cannot be updated or re-declared.
The value assigned to a const variable must be initialized at the time of declaration.
Example:
const z = 50;
console.log(z); // Output: 50
Differences Between var, let, and const
---
2. Functions in JavaScript
Functions in JavaScript are reusable blocks of code that perform a specific task. There are
different types of functions:
(i) Function Declaration
Declared using the function keyword.
Can be called before their definition due to hoisting.
Example:
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice")); // Output: Hello, Alice
(ii) Function Expression
A function assigned to a variable.
Not hoisted, meaning it must be defined before use.
Example:
let add = function (a, b) {
return a + b;
};
console.log(add(5, 3)); // Output: 8
(iii) Arrow Function (ES6)
A concise syntax for writing functions.
Does not have its own this context.
Example:
let multiply = (a, b) => a * b;
console.log(multiply(4, 5)); // Output: 20
(iv) Immediately Invoked Function Expression (IIFE)
A function that runs immediately after being defined.
Often used to avoid polluting the global scope.
Example:
(function () {
console.log("This runs immediately!");
})();
---
3. Default Functions in JavaScript and Their Functionalities
JavaScript has built-in functions that are commonly used:
(i) String Functions
(ii) Number Functions
(iii) Array Functions
---
4. Operators in JavaScript
Operators are symbols used to perform operations on variables and values.
(i) Arithmetic Operators
(ii) Assignment Operators
(iii) Comparison Operators
(iv) Logical Operators
---
Conclusion
JavaScript is a powerful language with flexible variable declarations, reusable functions, built-in
default functions, and essential operators. Understanding these fundamentals is crucial for
mastering JavaScript development.