JavaScript LGS


Javascript.txt

JavaScript is a programming language that is primarily used for web development. It allows 
developers to add interactive elements, dynamic content, and behavior to websites. It is a 
high-level, interpreted language, which means it is executed directly by web browsers without
the need for compilation.
It is an advanced programming language that makes web pages more interactive and
dynamic.

JavaScript is widely supported by all modern web browsers and is an essential component
of web development. It has a relatively easy-to-learn syntax and is known for its flexibility 
and versatility.


* Some key features and uses of JavaScript:

1. Client-Side Scripting: Most JavaScript code runs in the user's browser, meaning it can reduce server load and provide a smoother experience by processing data locally.

2. DOM manipulation: JavaScript provides powerful tools for manipulating the Document 
Object Model (DOM) of a web page. It allows developers to access and modify the structure, 
content, and styling of HTML elements dynamically.

3. Event handling: JavaScript enables developers to define event handlers that trigger 
specific actions or behaviors when certain events occur such as mouse clicks, keyboard 
input, and form submissions.

4. Asynchronous programming: With features like Promises and async/await, JavaScript can handle tasks that take time (like fetching data from a server) without blocking the rest of the code from running.

5. Frameworks and libraries: JavaScript has a vast ecosystem of frameworks and libraries 
that extend its capabilities. Examples include React, Angular, and React Native.

6. Versatile: JavaScript can be used in a variety of contexts and for different purposes, i.e., it can be used for both front-end (what users see) and back-end (server-side) development, especially with frameworks like Node.js. 
Frameworks like React Native allow developers to build mobile applications for iOS and Android using JavaScript, making it easier to create cross-platform apps.

7. Dynamically typed language: JavaScript is a dynamically typed language. This means that you don't need to specify the data type of a variable when you declare it. The type is determined at runtime based on the value assigned to the variable.

-----------------------------------------------------------------------------------------------------------------------------

* Datatypes in JS:

1. Number: Represents numeric values, including integers and floating-point numbers.

2. String: Represents sequences of characters enclosed in single quotes ('') or double quotes 
("").

3. Boolean: Represents a logical value, either true or false.

4. Null: Represents the intentional absence of any object value.

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

6. Symbol: Represents a unique identifier. Symbols are used to create private object 
properties and other advanced use cases.

# ----------------------------------------------------------------------------

Composite Data Types: 
In programming, composite data types are those that can hold multiple values or a collection of other data types. 

1. Object: Represents a collection of key-value pairs. Objects can be created using object literals {} or using the new Object() constructor.
2. Array: Represents an ordered list of values. Arrays are created using square brackets [] and can contain elements of any data type. 
3. Function: Represents reusable blocks of code that can be invoked or called. Functions can take parameters, perform operations, and return values.

III. Special Data Types:
1. BigInt: Represents arbitrary precision integers. It is used when numbers exceed the maximum value that can be represented by the Number type.
2. Date: Represents a specific date and time.

JavaScript_basics.txt

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
</body>

<!-- <script>
    // printing a statement in JavaScript
    // console.log("hello")

    // printing a warning in JavaScrript
    // console.warn("This is a warning")

    // printing an error in JavaScript
    // console.error('This is an error')

    // Datatypes - string, number, booelean
    // string - characters, special char, numbers everything written in single or double
    //          quotes
    // number - all numbers
    // boolean - True or False


    // checking a datatype 
    // console.log(typeof(10))
    // console.log(typeof('10'))

    // variables in JS - container to store any value / memory location
    // a = 10
    // b = 5
    // x = 7
    // y = 7
    // console.log(x == y)
    // console.log(x!=y)
    // console.log(x)
 
    // -------------------------------------------------------------------------
     //var a = "apple";
     //var b = "apple";
     //console.log(a == b);


     //var sym1 = Symbol("apple");
     //var sym2 = Symbol("apple");
    //console.log(sym1 == sym2);

    // -------------------------------------------------------------------------
   //  -------------------------------------------------------------------------

    // Operators -
    // Addition:
    // console.log(x+y)
    // sum = x+y
    // console.log(sum)
    
    // Subtraction:
    // difference = a-b
    // console.log(difference)
  
    // Multiplication:
    // console.log(a*b)

    // Division:
    // console.log(x/b)
    
    // Modulus:
    // console.log(x%b)

    // power:
    // console.log(a**b)


// ---------------------------------------------------------------
// let, var and const
// var - can be redeclared and reassigned, function scoped
// let - cannot be redeclared but can be reassigned, object scoped
// const - neither redeclared nor reassigned, object scoped

// var name=3
// console.log(a)
// var name=5
// console.log(a)


// let b = 23
// console.log(b)
// b = 2
// console.log(b)

// const x = 12
// console.log(x)
// x = 'hello'       // it will raise an error
// console.log(x)


// -----------------------------------------------------------------------------

Conditional (Ternary) Operator:

let num = 5;
let condition = num == 10 ? "true" : "not true";

console.log(condition);

// --------------------------------------------------------------------------

let age = 18;
let canVote = age >= 18 ? "Yes, can vote" : "No, cannot vote";

console.log(canVote);


</script> -->
</html>

--------------------------------------------------------------------------------------------
-----------------------------------

Hoisting_in_JS.txt

Hoisting:
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope, before the code is executed. 

1. Variable Hoisting
var Declarations: Variables declared with var are hoisted to the top of their enclosing function or global scope. However, only the declaration is hoisted, not the initialization.

console.log(x);
var x = 5;
console.log(x); 

In this example, var x is hoisted to the top, so the first console.log outputs undefined because the variable is declared but not yet initialized.

// ---------------------------------------------------------------------------------------------------

let and const Declarations: Variables declared with let and const are also hoisted,
but accessing them before the declaration results in a ReferenceError due to a "temporal dead zone(TDZ)

console.log(y);
let y = 10;

// ---------------------------------------------------------------------------------------------------

2. Function Hoisting
Function Declarations: Entire function declarations are hoisted, meaning you can call a function before it is defined in the code.

greet(); 

function greet() {
    console.log("Hello!");
}

// --------------------------------------------------------------------------------------------------

Function Expressions: If you assign a function to a variable (either with var, let, or const), only the variable declaration is hoisted, not the function itself.


sayHi(); 

var sayHi = function() {
    console.log("Hi!");
};

// ------------------------------------------------------------------------------------------------

Summary of Hoisting Behavior:

var: Declarations are hoisted, but not initializations. Resulting in undefined if accessed before assignment.

let and const: Declarations are hoisted but cannot be accessed before their initialization (temporal dead zone).

Function Declarations: Fully hoisted, can be called before their definition.

Function Expressions: Only the variable declaration is hoisted, leading to potential errors if invoked before assignment.

// -------------------------------------------------------------------------------------------------

To avoid confusion and potential errors caused by hoisting:

Declare variables at the top of their scope.

Prefer using let and const over var for better block scope management.
Always define functions before calling them, unless using function declarations.

JavaScript Tutorial

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="index.js"></script>
  </head>
  <body>
    <h1>Java Script</h1>
  </body>
  <!-- <script>
    console.log("hiii");
  </script> -->
</html>


index.js

// console.log("Hello World");
// console.warn("this is a warning!");
// console.error("this is an error");

// x = 5;
// console.log(x);

// console.log(x);
// var x = 5;

// console.log(a);
// let a = 10;

// console.log(b);
// const b = 5;
// console.log(a);
// var a = 10; // can re-declare and re assign the values
// var a = 12;

// let b = 16; // cannot re-declare but can re assign the value
// b = 12;
// console.log(b);

// const c = 100; // cannot re-declare nor re-assign the value
// c = 112;
// console.log(Name1);
// var Name1 = "abc";

// console.log(Name);
// const Name = "xyz";

// let a = "100";
// console.log(typeof a);

// let b = true;
// console.log(typeof b);

// let a = Symbol("apple");
// let b = Symbol("apple");
// console.log(a == b);

const a = 10;
const b = 20;
// const sum = a + b;
// console.log(sum);

// console.log(a == 10 && b == 10);

// console.log(a == 10 || b == 50);

// console.log(!(a == 10 || b == 50));

// console.log(!(a == 10));

// Ternary operator:

// let age = 18;
// user_age = prompt("enter your age: ");

// let canVote = user_age >= age ? "eligable to vote" : "not eligable";

// console.log(canVote);

// -------------------------------------------------------------

// alert("Hello World");
// confirm("are you sure, you want to delete this value ?");

// let num_1 = parseInt(prompt("enter number 1: "));
// let num_2 = parseInt(prompt("enter number 2: "));

// console.log(num_1 + num_2);

// let num_3 = 10;
// let newNumber = String(num_3);
// console.log(typeof newNumber);

// let num = 10;
// let str_1 = num.toString();
// console.log(str_1);
// console.log(typeof str_1);

// ----------------------------------------------------

// Template Literals in JS:

// let Name = prompt("enter you name: ");

// let greeting = `Hello ${Name}`;
// console.log(greeting);

// let Name1 = prompt("enter your name: ");
// let Age = prompt("enter your age: ");
// console.log(`the name of the user is ${Name1} and the age is ${Age}`);

// Conditional Statements:

let num_1 = 12;

if (num_1 == 10) {
  console.log("yes, num_1 = 10");
} else {
  console.log("no! num is not equal to 10");
}

Operators.txt

--------------------------------------------- OPERATORS IN JS ---------------------------------------------

* Some commonly used operators in JavaScript:

I. Arithmetic Operators:
1. + Addition: Adds two values together.
2. - Subtraction: Subtracts the second value from the first.
3. * Multiplication: Multiplies two values.
4. / Division: Divides the first value by the second.
5. % Modulo: Returns the remainder of the division.
6. ++ Increment: Increases the value by 1.
7. -- Decrement: Decreases the value by 1.

II. Assignment Operators:
1. = Assignment: Assigns a value to a variable.
2. += Addition assignment: Adds and assigns a value.
3. -= Subtraction assignment: Subtracts and assigns a value.
4. *= Multiplication assignment: Multiplies and assigns a value.
5. /= Division assignment: Divides and assigns a value.
6. %= Modulo assignment: Performs modulo operation and assigns a value.

III. Comparison Operators:
1. == Equal to: Checks if two values are equal.
2. === Strict equal to: Checks if two values are equal.
3. != Not equal to: Checks if two values are not equal.
4. !== Strict not equal to: Checks if two values are not equal.
5. > Greater than: Checks if the left value is greater than the right value.
6. < Less than: Checks if the left value is less than the right value.
7. >= Greater than or equal to: Checks if the left value is greater than or equal to the right value.
8. <= Less than or equal to: Checks if the left value is less than or equal to the right value.

IV. Logical Operators:
1. && Logical AND: Returns true if both operands are true.
2. || Logical OR: Returns true if at least one of the operands is true.
3. ! Logical NOT: Returns the inverse boolean value of the operand.

V. String Operators:
1. + Concatenation: Concatenates two strings together.

VI. Conditional (Ternary) Operator:
1. condition ? value1 : value2: Evaluates the condition and returns value1 if true, or value2 if false.


JavaScript_basics_2.txt

Conditional (Ternary) Operator:

let num = 5;
let condition = num == 10 ? "true" : "not true";

console.log(condition);

// --------------------------------------------------------------------------

let age = 18;
let canVote = age >= 18 ? "Yes, can vote" : "No, cannot vote";

console.log(canVote);

// -------------------------------------------------------------
// -------------------------------------------------------------

// logical operators in JS:

// && - Logical AND

// let a = 10;
// let b = 20;

// console.log(a == 10 && b != 20);

// -------------------------------------------------------------

// || - Logical OR

// console.log(a != 10 || b != 20);

// -------------------------------------------------------------

// ! - Logical NOT

// let c = 5;
// let d = 10;

// console.log(!(c < d));
// console.log(!(c > d));


--------------------------------------------------------------------------------------------
-----------------------------------

Common escape sequences characters in JavaScript:

\": Represents a double quote within a double-quoted string.
\': Represents a single quote within a single-quoted string.
\\: Represents a literal backslash.
\n: Represents a newline character.
\t: Represents a tab character.

---------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------

alert function :

In JavaScript, the alert() function is a built-in function that displays a dialog box 
with a message and an OK button. It is commonly used to show a simple notification  
to the user.

alert('hello world')

---------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------

confirm function :

In JavaScript, the confirm() function is used to display a dialog box with a message and 
two buttons - OK and Cancel buttons. The confirm() function is a simple way to get user 
input for a "yes" or "no" decisions and is commonly used for tasks where user confirmation 
is required before performing an action.

confirm("Do you want to delete this item?")

--------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------

prompt() is used take input from a user :

let userName = prompt("enter your name: ");
console.log("Hello", userName);


let num1 = prompt("enter number 1: ");
let num2 = prompt("enter number 2: ");
console.log(num1 + num2);

-----------------------------------------------------------------------------------------
----------------------------------------------------

// Type casting in JavaScript:

parseInt() is used to convert a string into a number :

let num1 = parseInt(prompt("enter number 1: "));
let num2 = parseInt(prompt("enter number 2: "));
console.log(num1 + num2);

String() is used to convert a number into a string:
let num = 42;
let str = String(num);
console.log(str);
console.log(typeof str);

toString() is also used to convert a number into a string:

let str_1 = num.toString();
console.log(str_1);
console.log(typeof str_1);



template_literals_Js.txt


ES6:
ECMAScript 6 (ES6), also known as ECMAScript 2015, is a significant update to the JavaScript language that introduced a variety of new features and improvements. Here are some of the key features of ES6:

Key Features of ES6: 

1. Let and Const: Introduced let and const for variable declarations, providing block scope.

let x = 10; // mutable
const y = 20; // immutable

2. Arrow Functions: A more concise syntax for writing function expressions.

const add = (a, b) => a + b;

3. Template Literals: Template literals allow you to create dynamic strings with embedded expressions and multi-line support.

4. Default Parameters, 
5. Promises(), 
6. Iterators and Generators and much more.


// ------------------------------------------------------------------------------------------------
// JavaScript Template Literals:

// a string using backticks (``). The expressions within ${} are evaluated and their values are 
inserted into the resulting string.
// ex-

let name1 = "Alice";
let greeting = `Hello, ${name1}!`;
console.log(greeting);

// --------------------------------------------------------------------------------------------

let Name = prompt("enter your name: ");
let Age = prompt("enter your age: ");
console.log(`the name of the user is ${Name} and the age is ${Age}`);


If_else_Js.txt

if-else in JavaScript:
In JavaScript, an "if-else" statement is a conditional statement that allows you to execute 
different blocks of code based on a specified condition. It's used to make decisions in your 
code by evaluating whether a condition is true or false.

Questions to practice "if-else":

let age = 18;
let user_age = parseInt(prompt("enter your age:"));
if (user_age >= age) {
  console.log("you are eligable to vote");
} else {
  console.log("not eligable");
}

//---------------------------------------------------------------------------------------------------------

let num1 = parseInt(prompt('enter a number'))
let num2 = parseInt(prompt('enter another number'))

if (num1 > num2){
    console.log(`${num1} is greater than ${num2}`)   
}
else if(num1 < num2){
    console.log(`${num1} is smaller than ${num2}`)
}
else{
    console.log(`${num1} and ${num2} are equal`)
}

//-----------------------------------------------------------------------------------------------------------


let num = parseInt(prompt('enter a number')

if (num>0){
    console.log('Positive')
}
else if(num<0){
    console.log('negative')
}
 else{
     console.log('neither positive nor negative')
}

//----------------------------------------------------------------------------------------------------------

let num = parseInt(prompt("enter a number: "));

if (num % 4 == 0) {
  console.log("Number is divisible by 4");
} else {
  console.log("Number is not divisible by 4");
}


//---------------------------------------------------------------------------------------------------------

let score = 85;

if (score >= 90) {
  console.log("You got an A.");
} else if (score >= 80) {
  console.log("You got a B.");
} else if (score >= 70) {
  console.log("You got a C.");
} else if (score >= 60) {
  console.log("You got a D.");
} else {
  console.log("You failed the exam.");
}

 index.js

// console.log("Hello World");
// console.warn("this is a warning!");
// console.error("this is an error");

// x = 5;
// console.log(x);

// console.log(x);
// var x = 5;

// console.log(a);
// let a = 10;

// console.log(b);
// const b = 5;
// console.log(a);
// var a = 10; // can re-declare and re assign the values
// var a = 12;

// let b = 16; // cannot re-declare but can re assign the value
// b = 12;
// console.log(b);

// const c = 100; // cannot re-declare nor re-assign the value
// c = 112;
// console.log(Name1);
// var Name1 = "abc";

// const Name = "xyz";
// Name = "abc";
// console.log(Name);

// let a = "100";
// a = 12;
// console.log(a);

// let b = true;
// console.log(typeof b);

// let a = Symbol("apple");
// let b = Symbol("apple");
// console.log(a == b);

const a = 10;
const b = 20;
// const sum = a + b;
// console.log(sum);

// console.log(a == 10 && b == 20);

// console.log(a == 10 || b == 50);

// console.log(!(a == 10 || b == 50));

// console.log(!(a == 10));

// Ternary operator:

// let age = 18;
// user_age = prompt("enter your age: ");

// let canVote = user_age >= age ? "eligable to vote" : "not eligable";

// console.log(canVote);

// -------------------------------------------------------------

// alert("Hello World");
// confirm("are you sure, you want to delete this value ?");

// let num_1 = parseInt(prompt("enter number 1: "));
// let num_2 = parseInt(prompt("enter number 2: "));

// console.log(num_1 + num_2);

// let num_3 = 10;
// let newNumber = String(num_3);
// console.log(typeof newNumber);

// let num = 10;
// let str_1 = num.toString();
// console.log(str_1);
// console.log(typeof str_1);

// let num1 = parseInt(prompt("enter a number: "));
// let num2 = parseInt(prompt("enter another number: "));
// let sum = num1 + num2;
// console.log(`the sum of ${num1} and ${num2} is ${sum}`);

// Template Literals in JS:

// let Name = prompt("enter you name: ");

// let greeting = `Hello ${Name}`;
// console.log(greeting);

// let Name1 = prompt("enter your name: ");
// let Age = prompt("enter your age: ");
// console.log(`the name of the user is ${Name1} and the age is ${Age}`);

// Conditional Statements:

// let num_1 = 12;

// if (num_1 == 10) {
//   console.log("yes, num_1 = 10");
// } else {
//   console.log("no! num is not equal to 10");
// }

// let num = parseInt(prompt("enter a number: "));

// if (num > 0) {
//   console.log("positive number");
// } else if (num < 0) {
//   console.log("negative number");
// } else {
//   console.log("number is zero");
// }

// let score = 85;

// if (score >= 90) {
//   console.log("you've got an A");
// } else if (score >= 80) {
//   console.log("you've got a B");
// } else if (score >= 70) {
//   console.log("you've got a C");
// } else if (score >= 60) {
//   console.log("you've got a D");
// } else if (score >= 50) {
//   console.log("you've got an E");
// } else {
//   console.log("you have failed the exam!");
// }

// let fruit = "apple";

// switch (fruit) {
//   case "banana":
//     console.log("found banana!");
//     break;
//   case "apple":
//     console.log("found apple!");
//     break;
//   case "kiwi":
//     console.log("found kiwi");
//     break;
//   default:
//     console.log("not found");
//     break;
// }

// let dayNumber = 3;
// switch (dayNumber) {
//   case 1:
//     console.log("Monday");
//     break;
//   case 2:
//     console.log("Tuesday");
//     break;
//   case 3:
//     console.log("Wednesday");
//     break;
//   case 4:
//     console.log("Thursday");
//     break;
//   case 5:
//     console.log("Friday");
//     break;
//   case 6:
//     console.log("Saturday");
//     break;
//   case 7:
//     console.log("Sunday");
//     break;
//   default:
//     console.log("Invalid day number!");
// }

const string = "hello";
console.log(string.length);
console.log(string[0]);

let greeting = "Hello, World!";
let greeting_2 = greeting.toUpperCase();

console.log(greeting_2);
console.log(greeting);

string_methods_JS.txt

Strings in Java Script :

1. strings are immutable in JavaScript. 
  This means that once a string is created, it cannot be changed. Any operation that appears      to modify a string actually creates a new string.

2. strings in JavaScript are indexed. Each character in a string can be accessed by its     position, starting from 0

let str = "Java Script";
console.log(str[0]);
console.log(str[5]);

// --------------------------------------------------------------------------------------------------

'+' operator is the most common way to concatenate strings

let firstName = prompt("enter your first Name: ");
let lastName = prompt("enter your last Name: ");
let fullName = firstName + " " + lastName;

console.log(fullName);

// --------------------------------------------------------------------------------------------------

// .length property: to find out the length of a string 

let string = "Hello";
console.log(string.length);

// --------------------------------------------------------------------------------------------------

                                                         STRING METHODS:

toUpperCase():
converts all characters in a string to uppercase.


let greeting = "Hello, World!";
let greeting_2 = greeting.toUpperCase();

console.log(greeting_2);


// --------------------------------------------------------------------------------------------------

toLowerCase():
converts all characters in a string to lowercase.

let str = "HAVE A LOVELY DAY!";
let str_2 = str.toLowerCase();

console.log(str_2);
console.log(str);    // original string

// --------------------------------------------------------------------------------------------------                 
trim():
removes whitespace from both ends of a string.

let message = "   Hello World!   ";
let trimmedMessage = message.trim();

console.log(trimmedMessage);

// -------------------------------------------------------------------------------------------------- 

includes()
checks if a string contains a specified substring and returns true or false.

let phrase = "The quick brown fox";
let hasFox = phrase.includes("fox");

console.log(hasFox);

// -------------------------------------------------------------------------------------------------- 

indexOf()
returns the index of the first occurrence of a specified substring. If not found, it returns -1.

let sentence = "I am learning the Java Script.";
let index = sentence.indexOf("Java");

console.log(index);

// -------------------------------------------------------------------------------------------------

slice()
This method extracts a section of a string and returns it as a new string.

let text = "Hello, World!";

let newText = text.slice(7, 12);
let newText_1 = text.slice(0, 5);
let newText_2 = text.slice(0, 6);

console.log(newText);
console.log(newText_1);
console.log(newText_2);

// -------------------------------------------------------------------------------------------------

split()
splits a string into an array of substrings based on a specified delimiter.

let fruits = "apple,banana,cherry";
let fruitsArray = fruits.split(",");

console.log(fruitsArray);


// --------------------


let sentence = "Learning JavaScript is fun and rewarding.";
let words = sentence.split(" ");

console.log(words);


switch.txt

Switch Statement in Java Script:

A switch expression is a way to choose between different options based on a value. 
Here’s how it works:

1. Evaluate the expression: You start with a value that you want to check.
2. Compare with cases: The value is compared to a list of possible options (cases).
3. Execute the match: If it finds a match, it runs the code associated with that option.
4. Default case: If there’s no match, it runs a special block of code called the default.

let fruit = "apple";

switch (fruit) {
  case "banana":
    console.log("found banana!");
    break;
  case "pine-apple":
    console.log("found apple!");
    break;
  case "kiwi":
    console.log("found kiwi!");
    break;
  default:
    console.log("not found");
    break;
}


// ---------------------------------------------------------------------

let dayNumber = 3;

switch (dayNumber) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  case 4:
    console.log("Thursday");
    break;
  case 5:
    console.log("Friday");
    break;
  case 6:
    console.log("Saturday");
    break;
  case 7:
    console.log("Sunday");
    break;
  default:
    console.log("Invalid day number!");
}

forLoop_Js(3).txt

/ WAP to check whether the user inputted number is prime or not:

let num = parseInt(prompt("Enter a number:"));

if (num <= 1) {
  console.log(num, " is not a prime number.");
} else {
  let isPrime = true; 

  for (let i = 2; i < num; i++) {
    if (num % i == 0) {
      console.log(num, " is not a prime number.");
      isPrime = false; 
      break; // No need to check further
    }
  }

  if (isPrime) {
    console.log(num, " is a prime number.");
  }
} 
forLoop_Js(2).txt

// Practice questions

// WAP to print all the even numbers from the given array-

numArray = [23, 44, 46, 51, 76, 13, 34, 67, 90, 17];

for (i = 0; i < numArray.length; i++) {
  if (numArray[i] % 2 == 0) {
    console.log(numArray[i], "even");
  }
}

// WAP to check whether the num in the given list are divisible by 4-

Array1 = [25, 16, 54, 44, 98, 72, 17, 30, 28, 40, 71, 83, 24];
// console.log(Array1);

for (i = 0; i < Array1.length; i++) {
  // console.log(Array1[i])
  let x = Array1[i];
  if (x % 4 == 0) {
    console.log(x, "divisible by 4");
  }
}

//---------------------------------------------------------------------------------------------------- 

// WAP to print the sum of first 10 natural numbers:
let sum = 0;

for (let i = 1; i <= 10; i++) {
  sum = sum + i;
}

console.log(sum);

//---------------------------------------------------------------------------------------------------- 

// WAP to print the factorial of a user inputted number
let num = parseInt(prompt("Enter a number: "));
let factorial = 1;
for (i = num; i >= 1; i--) {
  factorial = i * factorial;
}
console.log(`The factorial of ${num} is ${factorial}`);

for...in_&_for..of.txt
Difference between for loop, for in & for of:

1. for Loop (Traditional Loop)
The traditional for loop is used when you want to iterate over a block of code a specific number of times. It is typically used with numeric indices when you want to loop through arrays or perform repeated tasks.

let numbers = [10, 20, 30, 40];

for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);  
}

// Output: 10, 20, 30, 40

// --------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------

2. for in:
The for in loop is used to iterate over the keys of an object or the indices of an array. It is generally used when you want to work with the properties of an object or iterate over the enumerable properties of an object.

let person = {
  name: "John",
  age: 30,
  city: "New York",
};

for (let key in person) {
  console.log(key);
}

// ------------------------------------------------------------------------------

let person = {
  name: "John",
  age: 30,
  city: "New York",
};

for (let key in person) {
  console.log(key + ":" + person[key]);
}

// ------------------------------------------------------------------------------

let numbers = [10, 20, 30, 40];

for (let i in numbers) {
  console.log(i);
}

// ------------------------------------------------------------------------------

let numbers = [10, 20, 30, 40];

for (let i in numbers) {
  console.log(numbers[i]);
}

// --------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------

3. for of:
The for of loop is used to iterate over values of iterable objects such as arrays, strings, and other iterable data structures. It does not give you the index or key but directly provides the value of each element. 
for of loop does not work directly with objects.

let numbers = [10, 20, 30, 40];

for (let i of numbers) {
  console.log(i);
}

// ---------------------------------------------------------------------

let string = "hello";

for (let i of string) {
  console.log(i);
};


// ---------------------------------------------------------------------

let person = {
  name: "John",
  age: 30,
  city: "New York",
};

for (let key of person) {
  console.log(key);
}

// this throws an error as for of doesn't directly work on objects

// ------------------------------------------------------------------------

using Object.values():

let person = {
  name: "Alice",
  age: 25,
  city: "New York",
};

for (let value of Object.values(person)) {
  console.log(value);
}


while.txt

// initialization
// while (condition){
//     increment/decrement
// }



let i = 0;
while (i < 10) {
  console.log("Hello World");
  i++;
}

let i = 10;
while (i > 0) {
  console.log("Hello World");
  i--;
}

// ---------------------------------------

let i = 0;
let array = [10, 20, 30, 40, 50];
while (i < array.length) {
  console.log(array[i]);
  i++;
}

// ---------------------------------------

// WAP to print the list of even number upto 30 using while loop

let evenArray = []
let i=1
while(i<31){
    if (i%2==0){
        evenArray.push(i)
    }
    i++
}
console.log(evenArray)

// ---------------------------------------------------


StudentArray = [];
while (true) {
  let input = prompt("Are you a student?");
  let obj = {};
  if (input == "yes") {
    let fname = prompt("Enter first name");
    let lname = prompt("Enter last name");
    obj["fname"] = fname;
    obj["lname"] = lname;
    StudentArray.push(obj);
  } else {
    break;
  }
}
console.log(StudentArray);

// --------------------------------------------------
// do while:

let i = 0;
do {
  console.log("Hello World");
  i++;
} while (i < 10);


// -------------------------------------------------

let i = 5;
do {
  console.log("Hello World");
  i++;
} while (i < 4);

index.js

// let found = false;

// if (found) {
//   console.log("hello ");
// }

// --------------------------------------------------------------

// num = prompt(parseInt("enter a number: "));
// let found = false;

// for (let i = 0; i < 11; i++) {
//   if (i == num) {
//     console.log("number is found!");
//     found = true;
//     break;
//   }
// }
// if (!found) {
//   console.log("number not found!");
// }

// -------------------------------------------------------------

// do while:

// let i = 11;
// do {
//   console.log("Hello World");
//   i++;
// } while (i < 10);

// ---------------------------------------------------------------

// let array = [5, 10, 15, 20, 25];
// let sum = 0;
// let i = 0;

// while (i < array.length) {
//   if (array[i] % 2 === 0) {
//     sum += array[i];
//   }
//   i++;
// }

// console.log(sum);

// ---------------------------------------------------------------------

// functions in Java Script:

// function greet(a) {
//   console.log("Hello", a);
// }
// greet("Emma");

// -----------------------------------------------------

// function add(a, b) {
//   return a + b;
// }

// result = add(2, 3);
// console.log(result);

// ------------------------------------------------------

// Home Work :

// // Write a program that removes duplicate values from the given array using while loop.
// let array = [10, 20, 10, 30, 40, 20];


Functions_in_Js.txt

// Functions in JS

// Reusable block of code that can be executed whenever it is called
// Function returns a value

// creating our own functions-

// function greet(){
//     console.log('hello')
// }

// greet()

//--------------------------------------------------------------------------------

// function returns a value
// function greet2(){
//     return 'hello world'
// }

// let a = greet2()
// console.log(a)

// console.log(greet2())

// -------------------------------------
// Sum Function-
// function Sum(a,b){
//     return (a+b)
// }
// console.log(Sum(4,5))
// let n = Sum(7,8)
// console.log(n)

//--------------------------------------

function sum (a,b){
    return (a+b)
}
let num1 = parseInt(prompt('enter a number'))
let num2 = parseInt(prompt('enter another number'))
let solution = sum(num1,num2)
console.log(`the addition of ${num1} & ${num2} is ${solution}`)


//-------------------------------------

// Product Function-
// function product(a,b){
//     return a*b
// }
// product(7,10)                             //will not print the output 
// console.log(product(7,10))         //will prints the output


// -----------------------------

// Even Function-

// function even (a){
//     if (a%2==0){
//         return('even')
//     }
//     else{
//         return('odd')
//     }
// }
// console.log(even(3))

//-----------------------------------------------------------------

// user input

// let num = parseInt(prompt("Enter a number:"))
// console.log(even(num))

// odd function-

// function Odd(n){
//     if(n%2 != 0){
//         return 'Odd'
//     }
//     else{
//         return 'Even'
//     }
// }

// let num = parseInt(prompt())
// console.log(Odd(num))

//--------------------------------------------------------------------------

arrow_function.txt

// arrow functions - Arrow functions provide a concise syntax for
//                   writing functions in JavaScript.
//                   ()=>{}

// let greet = ()=> 'Hello World'
// console.log(greet())

//let add = function(a, b) {
//    return a + b;
//  };

// let add = (a, b) => a + b;

// -----------------------------------------------------------

// let wish = (name) => "hello " + name;
// console.log(wish("Emma"));

// let add = (a,b)=> a+b
// console.log(add(3,7))

// let prod = (x,y)=> {return x*y}
// console.log(prod(6,7))

// let square = (n) => {console.log(n*n)}
// square(7)
// square(3)

// let Square = (n)=> n*n
// console.log(Square(5))

// -----------------------------------------

let newfunction = (n) => {
    if (n%2==0) {
         console.log('even')
     }
else{
         console.log('odd')
     }
 }

newfunction(5)

//-----------------------------------------------------------------------------------------------------------

// even, odd questions using arrow function in one line code :
// this returns answer in 'true' or 'false'

// let even = (n) => n%2==0
// console.log(even(20))

// let odd = (n) => n%2!=0
// console.log(odd(11))

index.js

// Write a program that removes duplicate values from the given array using while loop.
// let array = [10, 20, 10, 30, 40, 20];
// let i = 0;
// let uniqueArray = [];

// while (i < array.length) {
//   if (!uniqueArray.includes(array[i])) {
//     uniqueArray.push(array[i]);
//   }
//   i++;
// }

// console.log(uniqueArray);

// ------------------------------------------------------------------
// functions :

// greet();
// greet_2("Emma");
// function greet() {
//   console.log("Hello World");
// }

// function greet_2(name) {
//   console.log("Hello", name);
// }
// // -------------------------------------
// myfunc();
// let myfunc = function() {
//   console.log("Have a nice day");
// };
// // -------------------------------------
// myfunc1();
// var myfunc1 = function() {
//   console.log("Have a nice day");
// };

// function add(a, b) {
//   sum = a + b;
//   return sum;
// }
// let result = add(1, 2);
// console.log(result);

// -----------------------------------------------------------

// function sum (a,b){
//     return (a+b)
// }
// let num1 = parseInt(prompt('enter a number'))
// let num2 = parseInt(prompt('enter another number'))
// let solution = sum(num1,num2)
// console.log(`the addition of ${num1} & ${num2} is ${solution}`)

// ----------------------------------------------------

// function checkEven(n) {
//   if (n % 2 == 0) {
//     console.log("even");
//   } else {
//     console.log("odd");
//   }
// }
// checkEven(11);

// --------------------------------------------

// function my_func(m, n) {
//   let total_sum = 0;
//   for (i = m; i <= n; i++) {
//     total_sum += i;
//   }
//   return total_sum;
// }
// console.log(my_func(1, 10));

// -------------------------------------------------

// function my_function(m, n) {
//   let sum = 0;
//   let i = m;
//   while (i <= n) {
//     sum += i;
//     i++;
//   }
//   return sum;
// }

// console.log(my_function(1, 10));

// -------------------------------------------------
// arrow functions:
// ()=>{}

// let greet = () => {
//   return "Hello World";
// };
// console.log(greet());

// let greet = (name) => {
//   return `Hello ${name}`;
// };
// console.log(greet("Mariya"));

// --------------------------------------------------------

// let add = (a, b) => {
//   return a + b;
// };
// console.log(add(5, 5));

// --------------------------------------------------------

// let square = (n)=> {console.log(n*n)}

// let even = (n) => n % 2 == 0;
// console.log(even(6));

Comments

Popular posts from this blog

Java

COMPUTER GRAPHICS IN BCA 3 YEAR