Day-6 (Variables and Functions (JavaScript) )
Day-6 (Variables and Functions (JavaScript) )
A variable is like a container that holds data. In JavaScript, you use variables to store
information that you can use and manipulate later in your code.
Declaring Variables
JavaScript provides three keywords to declare variables:
Example of var
var name = "Winnie Will"; // String variable
var age = 30; // Number variable
var isStudent = true; // Boolean variable
Example of let
let city = "New York"; // String variable
let temperature = 25.5; // Number variable (can be integer or float)
let isRaining = false; // Boolean variable
1
Example of const
const PI = 3.14159; // Constant number variable
const country = "USA"; // Constant string variable
• PI is a constant number variable holding the value 3.14159. This value cannot be changed.
• country is a constant string variable holding the value "USA". This value cannot be changed.
2
Variable Scope
• Global Scope: Variables declared outside any function are in the global scope and can be
accessed anywhere in the code.
• Function Scope: Variables declared with var inside a function are scoped to that function.
• Block Scope: Variables declared with let or const inside a block (e.g., inside {}) are scoped
to that block.
function testVar() {
var functionScopedVar = "I am function scoped";
console.log(functionScopedVar); // Accessible here
}
if (true) {
let blockScopedVar = "I am block scoped";
console.log(blockScopedVar); // Accessible here
}
3
Reassigning Variables
Variables declared with var and let can be reassigned.
Functions
1. Basic Function
A basic function in JavaScript can be defined using the function keyword.
// Function to greet a user
function greet() {
console.log("Hello, world!");
}
4
2. Function with Parameters
Functions can take parameters, which allow you to pass data into them.
// Function to greet a user with a name
function greetUser(name) {
console.log("Hello, " + name + "!");
}
6. Arrow Functions
ES6 (One of the key features introduced in ES6 is arrow functions) introduced arrow functions, which
offer a shorter syntax.
// Arrow function to add two numbers
let add = (a, b) => {
return a + b;
};
function testScope() {
let localVar = "I'm local!";
console.log(localVar); // Output: I'm local!
}
testScope();
// console.log(localVar); // Error: localVar is not defined
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
if (b !== 0) {
return a / b;
} else {
7
return "Error: Division by zero";
}
}