Beginners Introduction Guide To JavaScript Code

Beginners Introduction Guide To JavaScript Code

JavaScript is a high-level, dynamic, and interpreted programming language. It is used to add interactivity and other dynamic elements to websites.

Here are some basics of JavaScript with code examples:

Variables: 

variables are used to store values in JavaScript. You can declare a variable with the “let” keyword, like this:

let x = 10;

let name = “John”;

let age = 30;

let isStudent = false;

let weight = 75.5;

let address = “123 Main St.”;

Data Types:

 JavaScript has several data types, including numbers, strings, and booleans. Here’s an example of each:

let num = 10;

let str = “Hello World”;

let bool = true;

let num1 = 20;

let num2 = -10;

let str1 = “Hello”;

let str2 = ‘JavaScript’;

let bool1 = true;

let bool2 = false;

Arithmetic Operations: 

JavaScript supports basic arithmetic operations like addition, subtraction, multiplication, and division. Here’s an example:

let x = 10;

let y = 5;

let sum = x + y;

let difference = x – y;

let product = x * y;

let quotient = x / y;

let x = 10;

let y = 20;

let sum = x + y;

let difference = x – y;

let product = x * y;

let quotient = x / y;

let modulo = x % y;

let increment = x++;

let decrement = y–;

Conditional Statements: 

Conditional statements are used to execute different blocks of code based on conditions. The if-else statement is the most common type of conditional statement in JavaScript. Here’s an example:

let x = 10;

if (x > 5) {

  console.log(“x is greater than 5”);

} else {

  console.log(“x is not greater than 5”);

}

let grade = 85;

if (grade >= 90) {

  console.log(“A”);

} else if (grade >= 80) {

  console.log(“B”);

} else if (grade >= 70) {

  console.log(“C”);

} else {

  console.log(“F”);

}

let day = “Sunday”;

switch (day) {

  case “Monday”:

    console.log(“Today is Monday”);

    break;

  case “Tuesday”:

    console.log(“Today is Tuesday”);

    break;

  case “Wednesday”:

    console.log(“Today is Wednesday”);

    break;

  case “Thursday”:

    console.log(“Today is Thursday”);

    break;

  case “Friday”:

    console.log(“Today is Friday”);

    break;

  case “Saturday”:

    console.log(“Today is Saturday”);

    break;

  default:

    console.log(“Today is Sunday”);

}

Functions: 

Functions are blocks of code that can be executed when they are called. Here’s an example:

function greeting() {

  console.log(“Hello World”);

}

greeting();

function add(x, y) {

  return x + y;

}

let result = add(10, 20);

console.log(result);

function greet(name) {

  console.log(“Hello ” + name);

}

greet(“John”);

function calculateArea(width, height) {

  return width * height;

}

let area = calculateArea(10, 20);

console.log(area);

function checkOddEven(num) {

  if (num % 2 === 0) {

    return “Even”;

  } else {

    return “Odd”;

  }

}

let result = checkOddEven(10);

console.log(result);

function generateRandomNumber() {

  return Math.floor(Math.random() * 100);

}

let randomNumber = generateRandomNumber();

console.log(randomNumber);

These are just some of the basics of JavaScript. There is much more to learn, but these basics will give you a good foundation to start building your skills.

JavaScript Loops:

JavaScript has two types of loops: for loops and while loops. Here are examples of each:

For Loop:

for (const i = 0; i < 5; i++) {

  console.log(“Iteration ” + (i + 1));

}

This code will output:

Iteration 1

Iteration 2

Iteration 3

Iteration 4

Iteration 5

While Loop:

const i = 0;

while (i < 5) {

  console.log(“Iteration ” + (i + 1));

  i++;

}

This code will output:

Iteration 1

Iteration 2

Iteration 3

Iteration 4

Iteration 5

In addition to these two loops, there is also the do-while loop, which is similar to the while loop, but with a slight difference in the way the condition is checked. Here’s an example:

const i = 0;

do {

  console.log(“Iteration ” + (i + 1));

  i++;

} while (i < 5);

This code will output:

Iteration 1

Iteration 2

Iteration 3

Iteration 4

Iteration 5

These are the basics of JavaScript loops. You can use them to repeat a block of code multiple times based on conditions.

JavaScript Comments

In JavaScript, you can add comments in your code to describe what it does or to temporarily ignore parts of the code. There are two types of comments: single-line comments and multi-line comments.

Single-line comment:

// This is a single-line comment

Multi-line comment:

/* 

  This is a multi-line 

  comment

*/

Here’s an example that shows how comments can be used in a code:

// This is a single-line comment

/* 

  This is a multi-line 

  comment

*/

const name = “John”; // This is also a single-line comment

// The code below will print the value of the variable “name”

console.log(name); 

JavaScript Data Types

In JavaScript, there are seven basic data types:

Number: Used to represent numbers. Example: const num = 42;

String: Used to represent a sequence of characters. Example: const name = “John”;

Boolean: Used to represent a logical value of either true or false. Example: const isMarried = true;

Undefined: Represents a value that has not been assigned. Example: const age; console.log(age); // Output: undefined

Null: Represents a value that is explicitly null. Example: const address = null;

Symbol: Used to create unique identifiers for objects. Example: const symbol = Symbol(“description”);

Object: Used to represent a collection of key-value pairs. Example: const person = { name: “John”, age: 30 };

In JavaScript, variables have a dynamic type and can change their type based on the value assigned to them. The typeof operator can be used to check the type of a variable.

Example:

const num = 42;

console.log(typeof num); // Output: “number”

const name = “John”;

console.log(typeof name); // Output: “string”

const isMarried = true;

console.log(typeof isMarried); // Output: “boolean”

const age;

console.log(typeof age); // Output: “undefined”

const address = null;

console.log(typeof address); // Output: “object”

const symbol = Symbol(“description”);

console.log(typeof symbol); // Output: “symbol”

const person = { name: “John”, age: 30 };

console.log(typeof person); // Output: “object”

JavaScript Arrays

An array in JavaScript is a data structure that stores a collection of values. You can access individual values of an array by referring to their index number. Arrays are declared using square brackets [] and items are separated by commas.

Here’s an example of an array in JavaScript:

const fruits = [“apple”, “banana”, “cherry”];

JavaScript provides several built-in methods for working with arrays. Here are some commonly used methods with examples:

length property: returns the number of elements in an array.

const fruits = [“apple”, “banana”, “cherry”];

console.log(fruits.length); // Output: 3

push() method: adds an element to the end of an array.

const fruits = [“apple”, “banana”, “cherry”];

fruits.push(“orange”);

console.log(fruits); // Output: [“apple”, “banana”, “cherry”, “orange”]

pop() method: removes the last element from an array and returns it.

const fruits = [“apple”, “banana”, “cherry”];

const lastFruit = fruits.pop();

console.log(fruits); // Output: [“apple”, “banana”]

console.log(lastFruit); // Output: “cherry”

unshift() method: adds an element to the beginning of an array.

const fruits = [“apple”, “banana”, “cherry”];

fruits.unshift(“peach”);

console.log(fruits); // Output: [“peach”, “apple”, “banana”, “cherry”]

shift() method: removes the first element from an array and returns it.

const fruits = [“apple”, “banana”, “cherry”];

const firstFruit = fruits.shift();

console.log(fruits); // Output: [“banana”, “cherry”]

console.log(firstFruit); // Output: “apple”

splice() method: adds or removes elements from an array.

const fruits = [“apple”, “banana”, “cherry”];

fruits.splice(1, 0, “lemon”, “lime”);

console.log(fruits); // Output: [“apple”, “lemon”, “lime”, “banana”, “cherry”]

These are some of the most commonly used array methods in JavaScript. You can use these methods to manipulate arrays and perform various operations on them.

JavaScript Objects

In JavaScript, an object is a collection of key-value pairs that store data. Objects are declared using curly braces {} and the keys and values are separated by colons.

Here’s an example of an object in JavaScript:

const person = {

  name: “John”,

  age: 30,

  location: “San Francisco”

};

You can access the values of an object using the dot notation or square bracket notation.

Here’s an example of how to access the values of an object using the dot notation:

const person = {

  name: “John”,

  age: 30,

  location: “San Francisco”

};

console.log(person.name); // Output: “John”

console.log(person.age); // Output: 30

console.log(person.location); // Output: “San Francisco”

Here’s an example of how to access the values of an object using the square bracket notation:

const person = {

  name: “John”,

  age: 30,

  location: “San Francisco”

};

const nameKey = “name”;

const ageKey = “age”;

const locationKey = “location”;

console.log(person[nameKey]); // Output: “John”

console.log(person[ageKey]); // Output: 30

console.log(person[locationKey]); // Output: “San Francisco”

You can also add new properties or change the values of existing properties in an object.

Here’s an example of how to add a new property to an object:

const person = {

  name: “John”,

  age: 30,

  location: “San Francisco”

};

person.email = “john@example.com”;

console.log(person); // Output: { name: “John”, age: 30, location: “San Francisco”, email: “john@example.com” }

Here’s an example of how to change the value of an existing property in an object:

const person = {

  name: “John”,

  age: 30,

  location: “San Francisco”

};

person.age = 35;

console.log(person); // Output: { name: “John”, age: 35, location: “San Francisco” }

Objects are widely used in JavaScript to store data and represent real-world objects. You can use objects to create more complex data structures and manage your data more effectively.

JavaScript String Methods

JavaScript provides several built-in methods for manipulating strings, some of the commonly used ones are:

length: Returns the length of the string. 

Example: var name = “John”; console.log(name.length); // Output: 4

concat: Joins two or more strings together. 

Example: var firstName = “John”; var lastName = “Doe”; console.log(firstName.concat(” “, lastName)); // Output: “John Doe”

toUpperCase: Converts the string to uppercase. 

Example: var name = “John”; console.log(name.toUpperCase()); // Output: “JOHN”

toLowerCase: Converts the string to lowercase. 

Example: var name = “John”; console.log(name.toLowerCase()); // Output: “john”

charAt: Returns the character at the specified index. 

Example: var name = “John”; console.log(name.charAt(0)); // Output: “J”

indexOf: Returns the index of the first occurrence of the specified value, or -1 if it is not found. 

Example: var name = “John”; console.log(name.indexOf(“o”)); // Output: 1

slice: Extracts a part of the string and returns it as a new string. 

Example: var name = “John”; console.log(name.slice(0, 2)); // Output: “Jo”

replace: Replaces the first occurrence of the specified value with a new value. 

Example: var name = “John”; console.log(name.replace(“J”, “j”)); // Output: “john”

trim: Removes whitespaces from both ends of the string. 

Example: var name = ” John “; console.log(name.trim()); // Output: “John”

These are just a few of the many string methods available in JavaScript, each with its own specific use case. Understanding and utilizing these methods can greatly simplify string manipulation tasks in your code.

JavaScript Classes

JavaScript added class syntax with ECMAScript 6 (ES6) as a way to write reusable code and create objects. A class is a blueprint for creating objects that have similar properties and methods.

Here’s an example of a class in JavaScript:

class Person {

  constructor(name, age) {

    this.name = name;

    this.age = age;

  }

  greet() {

    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);

  }

}

In the above example, the Person class has two properties: name and age, and a method greet that prints a greeting message.

To create an object from this class, you use the new operator and call the constructor function:

const person = new Person(“John”, 30);

person.greet(); 

// Output: Hello, my name is John and I am 30 years old.

You can also extend a class to create a subclass and inherit properties and methods from the parent class:

class Student extends Person {

  constructor(name, age, major) {

    super(name, age);

    this.major = major;

  }

  study() {

    console.log(`I am studying ${this.major}.`);

  }

}

const student = new Student(“Jane”, 20, “Computer Science”);

student.greet(); 

// Output: Hello, my name is Jane and I am 20 years old.

student.study();

// Output: I am studying Computer Science.

In the above example, the Student class extends the Person class and adds a new property major and a method study. The super keyword is used to call the constructor of the parent class and pass along the required properties.

Classes in JavaScript provide a way to write organized and reusable code, making it easier to maintain and extend your codebase.