top of page
  • Writer's pictureRajesh Dhiman

Chapter 2: Understanding the Basics

Understanding Variables in JavaScript


Variables are the building blocks of JavaScript. They act as containers for storing data values, allowing you to manipulate and use data throughout your code.


Declaring Variables


In JavaScript, variables can be declared using let, const, and var.


let: Used for variables that can be reassigned.

const: Used for variables that should not be changed.

var: An older way to declare variables, but it’s best to avoid it due to its scope-related issues.


Example:

let userName = "Alice";
const birthYear = 1995;
var favoriteColor = "blue"; // Not recommended

Understanding Data Types


JavaScript has several data types, categorized into primitives and objects.


Primitive Types


String: Represents textual data.

Example: let name = "John";

Number: Represents numerical data.

Example: let age = 30;

Boolean: Represents logical values.

Example: let isStudent = false;

Undefined: Represents a variable that has been declared but not assigned a value.

Null: Represents an empty or non-existent value.


Objects


Objects are collections of key-value pairs, and they can be more complex data types like arrays and functions.


Example:

let hobbies = ["reading", "gaming", "sports"]; // Array
let address = { city: "New York", zip: "10001" }; // Object

JavaScript Operators and Expressions


Operators are symbols used to perform operations on operands (values and variables). They can be categorized into arithmetic, comparison, logical, and assignment operators.


Arithmetic Operators


Arithmetic operators perform mathematical calculations.


Addition (+): Adds two numbers.

Subtraction (-): Subtracts one number from another.

Multiplication (*): Multiplies two numbers.

Division (/): Divides one number by another.

Modulus (%): Returns the remainder of a division operation.


Example:

let a = 10;
let b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.3333
console.log(a % b); // 1

Comparison Operators


Comparison operators compare two values and return a boolean result (true or false).


Equal (==): Checks if two values are equal.

Strict Equal (===): Checks if two values are equal and of the same type.

Not Equal (!=): Checks if two values are not equal.

Greater Than (>): Checks if the left operand is greater than the right.

Less Than (<): Checks if the left operand is less than the right.


Example:

let x = 5;
console.log(x == "5"); // true
console.log(x === "5"); // false
console.log(x != 8); // true
console.log(x > 3); // true

Logical Operators


Logical operators are used to combine multiple conditions.


AND (&&): Returns true if both operands are true.

OR (||): Returns true if at least one operand is true.

NOT (!): Reverses the boolean value of its operand.


Example:

let isAdult = true;
let hasTicket = false;
console.log(isAdult && hasTicket); // false
console.log(isAdult || hasTicket); // true
console.log(!isAdult); // false

Control Structures in JavaScript


Control structures direct the flow of your code, allowing you to make decisions and execute blocks of code conditionally or repeatedly.


If Statements


If statements execute code blocks based on specified conditions.


Example:

let age = 18;
if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}

Switch Statements


Switch statements evaluate an expression and execute code blocks based on matching case clauses.


Example:

let fruit = "apple";
switch (fruit) {
  case "banana":
    console.log("Banana is yellow.");
    break;
  case "apple":
    console.log("Apple is red.");
    break;
  default:
    console.log("Unknown fruit.");
}

Loops


Loops are used to execute a block of code repeatedly until a specified condition is met. They include for, while, and do...while loops.


For Loop


Repeats a block of code a specific number of times.


Example:

for (let i = 0; i < 5; i++) {
  console.log("Iteration:", i);
}

While Loop


Repeats a block of code as long as a specified condition is true.


Example:

let i = 0;
while (i < 5) {
  console.log("While loop iteration:", i);
  i++;
}

Do…While Loop


Similar to a while loop, but it executes the block of code at least once before checking the condition.


Example:

let j = 0;
do {
  console.log("Do...While loop iteration:", j);
  j++;
} while (j < 5);

FAQs


1. What is a variable in JavaScript?

A variable is a container for storing data values.

2. What are the different data types in JavaScript?

JavaScript supports several data types, including string, number, boolean, array, object, undefined, and null.

3. How do you perform arithmetic operations in JavaScript?

Use arithmetic operators like +, -, *, /, and %.


One-Liner Questions


What does === do in JavaScript?

It checks if two values are equal and of the same type.

How do you create a loop in JavaScript?

Use a for, while, or do...while loop.


Coding Problems


1. Problem 1: Check Positive or Negative

• Write a function that checks if a number is positive or negative.

function checkSign(num) {
  return num >= 0 ? "Positive" : "Negative";
}
console.log(checkSign(5)); // Positive

2. Problem 2: Sum of Array Elements

• Create a function that returns the sum of all elements in an array.

function sumArray(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum += arr[i];
  }
  return sum;
}
console.log(sumArray([1, 2, 3, 4])); // 10

3. Problem 3: Find Maximum Number

• Write a function that finds the maximum number in an array.

function findMax(arr) {
  let max = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > max) {
      max = arr[i];
    }
  }
  return max;
}
console.log(findMax([3, 7, 2, 9])); // 9

External Links


1. JavaScript Guide - Mozilla Developer Network - Comprehensive JavaScript Guide

3. JavaScript Fundamentals - Codecademy - JavaScript Fundamentals

1 view0 comments

Comments


bottom of page