0% found this document useful (0 votes)
17 views7 pages

JavaScript Basics: Variables, Loops, Functions

The document is a checklist covering various programming concepts including variable declaration, data types, operators, decision-making structures, loops, and functions in JavaScript. It provides examples and explanations for each topic, such as the differences between function declarations and expressions, the use of arrow functions, and type conversion methods. Additionally, it includes notes on best practices and common pitfalls in programming.

Uploaded by

diptowin101
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views7 pages

JavaScript Basics: Variables, Loops, Functions

The document is a checklist covering various programming concepts including variable declaration, data types, operators, decision-making structures, loops, and functions in JavaScript. It provides examples and explanations for each topic, such as the differences between function declarations and expressions, the use of arrow functions, and type conversion methods. Additionally, it includes notes on best practices and common pitfalls in programming.

Uploaded by

diptowin101
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Coddy Checklist:

1:

[Link]("haha gg")

//

/* */

2:

let age = 19 //number

let name = "Dipto B." //string

let married = false //Boolean

camelCase!!!!!!!

variable Declare vs variable Ini alize

const pi = 3.14

3: Arithme c + Rela onal + Logical (Operator)

+-*/

modulo (%)

Self opera on: a += 3, a *= 7

Comparison: ==, >, <, !=, >=, <=

== === != !== (Type Coercion != conversion)

//Part 2: Logical Operator

&& || !

!(A && B) == (!A) || (!B), !(A || B) == (!A) && (!B)

#What is truthy??

[h ps://[Link]/share/681254d3-674c-800d-a21c-1577e923e7ef]
Number(value), String(value), Boolean(value) //Type conversion

4: Decision Making + Condi onal Statement

()= Parenthesis

{}= Curly Braces

[]= Bracket

if (condi on) { code to be executed }

if else () { }

else { } //no condi on

if (){ if() { } else { } } else { } //nested if-else

switch (variable) { case 1: break; default: } /*for exact value comparison of single variable in case*/

switch (true) { case (any condi on): break; default: } /*for using range of a variable(condi ons) in case*/

using condi on in case! (h ps://[Link]/share/68186038-13dc-800d-931c-38b97a3184b1)

5: IO (input/output)

[Link]("Ami", variable, 72+42)

[Link](`His age is: ${variable}`) /*back cks `` instead of quota on marks "" && ${variable}*/

parseInt(variable) parseFloat(variable) /*Type conversion be er than Number(variable)?*/


{h ps://[Link]/share/681ce88f-598c-800d-8010-9998d0ba8e48}

Number vs parseInt /*[Link](parseInt("123abc")); // Output: 123 */

Boolean(variable) String(variable)

Project: "Bill split Calculator"


6: Loops;

For loop: execute 1 me at least! (not really )

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

[Link](i);

//internal/ single variable

let sum_numbers = 0;

for (let i = 1; i <= 100; i++) {

sum_numbers += i;

[Link](sum_numbers);

//mul ple variable

For Loop projects:

1. Hello World Countdown

2. Mul plica on Table

3. Smallest power of 2 great than any Input number

4. Factorial Number Genera on //(same as Sum of 1--100)

While loop: if condi on but loop!

while (condi on) {

code;

}
do...while loop: execute 1 me at least! (regardlesss of Condi on!)

do {

code;

} while (condi on);

//[h ps://[Link]/share/682bd9d4-5bdc-800d-866f-854bedbe4383]

nested loop! // using different i variables is best than block-scoping/let!

for (let i = 0; i < 3; i++) { //outer loop

for (let j = 0; j < 3; j++) { //inner loop

[Link](`i: ${i}, j: ${j}`);

7: Func ons;

//Declare:

func on func onName() {

code;

return

//func on Call:

func onName();
//func on arguments: a value that you pass into the func on when you call it!

func on isEven(number) {

if (number % 2 === 0) {

[Link](`${number} is even`);

} else {

[Link](`${number} is odd`);

--return-- return is for the func on to provide a result.

//return vs [Link]

//Why do we even need to use return in a func on? Can't we just use [Link]? (ans: return can set the
value of func on itself, [Link] can't. It just prints!)

--func on Expression-- func on (with no name) but inside a Variable!

//Types:

1. named

2. anonymous

//code example:

let add = func on sum(a, b) {

return a + b;

};

[Link](add(3, 5)); //**(func on Name DOES NOT MATTER, use Variable name instead!)
// Why use Func on Expression (instead of normal func on)?

> FE is not Hoisted

> Can be defined without any name (//**takes the name of Variable)

> Flexible

> You can change the Name of the func on!

--Default Parameter (in func on)-- like a Variable!

//code example:

func on greet(name, gree ng = "Hello") {

[Link](`${gree ng}, ${name}!`);

greet("Alice"); // Output: Hello, Alice!

greet("Bob", "Hi"); // Output: Hi, Bob!

//**the second argument overrides the default value.

--Arrow Func ons-- =>

short

no name (//truly no name, not even op onal!)

you can't use an arrow func on standalone, without using it as aroow func on expeession (ans: no name)

//code example:

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


Notes:
> [Link](`vName = ${vName}`)

> let a = parseInt(inp)

> let a = inp

> if (rnd%2 == 0) //even

else if (rnd%2 != 0) //odd

> NaN = Not a Number!

> Concatena on //"5" + 5 = 55

> condi on ? expression_if_true : expression_if_false; //ternary operator/condi on

> break;

> con nue; //skip this code!

> infinite loop!!

> Factorial of 3! = 1x2x3

> for (let i=0; //block-scoped variable, only for use inside block!

> Why use ; ???

> return vs [Link] ?? //h ps://[Link]/share/6839b4d0-be64-800d-a960-04eec171aee3

> Sigma Nota on Σ //i.e summa on

> i = index

> arguments == //(addi onal inputs)

> parameters == //(changable placeholder variable that are aleady in program)

> expressions == //h ps://[Link]/share/68389dfd-c958-800d-9f88-e35352d1af0c

> Hois ng = /*is a behavior in certain programming languages where variable and func on declara ons are
moved to the top of their containing scope during the compile phase, before the code is executed*/

> variable = [Link] on, [Link] alizatn/value

> func on = [Link] on, [Link]fine/body

> let vs var (ans: in var, declara on is hoisted!)

Common questions

Powered by AI

Using 'const' for variable declaration indicates that the variable's identifier cannot be reassigned, providing a predictable fixed value within its context, which is essential when defining constants like `const pi = 3.14` . This differs from 'let,' which allows reassignment within the same block, and 'var,' which is function-scoped and can be hoisted, potentially leading to unexpected overwrites or values . Choosing 'const' aids in reducing mutation and side-effects, promoting functional programming principles .

Function declaration defines a named function using the "function" keyword followed by a name and parentheses, allowing the function to be used before it's declared due to hoisting. Function expression involves defining a function inside a variable without a name, making it an anonymous function that is not hoisted, meaning it must be defined before use . Choosing function expressions offers flexibility since they allow changing the function name and are not hoisted, which can help in avoiding errors due to hoisting behaviors .

The 'break' statement terminates the current loop immediately, resuming control after the loop. 'Continue' skips the current iteration and proceeds to the next one. For example, consider a loop over an array where we want to break upon finding a specific value: ``` for (let i = 0; i < array.length; i++) { if (array[i] === 'stop') { break; } if (array[i] % 2 !== 0) { continue; } console.log(array[i]); } ``` This loop breaks out completely if 'stop' is encountered, but skips odd numbers, continuing with the next iteration . Proper use of break and continue can optimize loop flow efficiency .

For loops are ideal for iterating a known number of times, such as iterating through arrays, since they combine initialization, condition, and increment in one line. While loops are suitable for scenarios where the number of iterations is not known and the loop needs to continue until a condition becomes false. Do-while loops guarantee at least one execution regardless of the condition, making them useful when the loop must run at least once before checking the condition . For example, use a for loop for fixed iterations, while use a while loop for undefined iterations based on dynamic conditions .

Type coercion in JavaScript happens implicitly, converting values between types during operations or comparisons, sometimes leading to unexpected results. For example, using '==' instead of '===' allows coercion, such as when comparing `5 == '5'`, which returns true due to coercion. Conversion, however, is explicit, like using `Number('5')` to convert a string to a number explicitly, ensuring type safety . Coercion can lead to unexpected errors, whereas conversion ensures clarity and type predictability .

Logical operators (&&, ||, !) combine or invert conditions in conditional statements. They help evaluate multiple conditions together. For example, a nested if-else condition using logical operators can look like this: ``` if (age > 18 && !married) { if (hasID) { console.log('Eligible for entry'); } else { console.log('ID required'); } } else { console.log('Not eligible'); } ``` This evaluates whether 'age' is greater than 18 and not married, proceeding to check 'hasID' for eligibility .

Arrow functions provide a shorter syntax for writing functions and do not have their own 'this' context, making them ideal for non-method functions. They preserve the 'this' value of the enclosing context, reducing the risks of bugs in callbacks where 'this' might refer to unexpected objects . This behavior can benefit cleaner code and avoid common mistakes in object-oriented programming .

Hoisting moves declarations to the top of its scope before code execution. For variables declared with 'var,' this means they are initialized as 'undefined' at the top of their function scope, leading potentially to logic errors if relied on before explicit initialization. For functions, hoisting allows functions to be invoked before they appear in code. For example, invoking a function before its line of definition due to its declaration being hoisted . Understanding hoisting necessitates careful planning of declaration order, especially with 'var', to prevent unexpected behavior .

Using backticks allows for template literals which enable multi-line strings and the embedding of expressions directly within a string. For instance, `console.log(`${name} is ${age} years old.`);` evaluates the expressions within `${}` and incorporates them seamlessly. This is preferred over regular quotes because it simplifies string interpolation and enhances readability, eliminating the need for concatenation . Backticks enhance code clarity and efficiency when handling dynamic strings .

The ternary operator simplifies conditional statements by allowing inline condition checks within an expression, `condition ? expression_if_true : expression_if_false;`. For example, simplifying a check for minimum value: `const min = (a < b) ? a : b;`. It provides a concise alternative to multi-line if-else statements, improving readability when dealing with simple conditions . It is particularly helpful for quick assignments based on conditions .

You might also like