Skip to content

Latest commit

 

History

History
324 lines (260 loc) · 7.53 KB

learn-javascript.md

File metadata and controls

324 lines (260 loc) · 7.53 KB

Learn JavaScript Basics

Helpful links

  1. Javascript Info(Read it when you get time!)

Function declaration vs Function expression

Reference

Function declaration

function sayHi() {
  alert( "Hello" );
}

Function expression

let sayHi = function() {
  alert( "Hello" );
};

// Or
let sayHi = () => { alert("Hello") }; // Arrow function

No matter how the function is created, a function is a value. Both examples above store a function in the sayHi variable.

Implicit vs Explicit return in Arrow functions

// An arrow function with {}, no automatic return
const addOneA = (num) => { num + 1 }; 
console.log(addOneA(1)); // undefined

// An arrow function without {}, will automatically return
const addOneB = (num) => num + 1; 
console.log(addOneB(1)); // 2

addOneA is equivalent to

function addOneA(num){
  num + 1;
}

addOneB is equivalent to

function addOneB(num){
  return num + 1;
}

Export and Import

Read this as this is an important concept.

import vs require

import (ES Modules syntax) require (CommonJS Modules syntax)
Summary

It is the latest standard for working with modules in JavaScript and is supported in modern browsers and environments that transpile or support ES6, like TypeScript or Babel.

It was not originally part of JavaScript, but was adopted as the standard for Node.js, which has been routinely used in JavaScript server-side development.

While Node.js historically used CommonJS, it now also supports ES6 modules.

Exports

Static (pre-defined). The structure of the module's exports is determined when the code is parsed, not while running.

This static nature allows tooling such as bundlers and linters to analyze the code without executing it, enabling features like better tree-shaking and faster load times in browsers.

For example:
// myModule.js
export function myFunc() { /*...*/ }
export const MY_CONST = 123;

Computed during runtime. The exports in a module are determined during the execution of the code.

For example:
// myModule.js
if (process.env.NODE_ENV === 'development') {
  module.exports.debug = function debug() {
    console.log('Debugging...');
  }
} else {
  module.exports.log = function log() {
    console.log('Logging...');
  }
}
Loading Modules

Can be asynchronous, allowing efficient, selective loading of module parts.
This can result in faster load times and better performance.

For example:

import { myFunc } from './myModule.js';
myFunc();

Synchronous (loads modules one by one).
Always loads entire module, which could affect performance if the module is large.

For example:
const { debug, log } = require('./myModule.js');
if(debug) debug();
if(log) log();
Full Example Make sure to export the function first.
// somefile.js
export function sayHello() {
  console.log("Hello, world!");
}

console.log("somefile has been loaded!");

Then import it

// main.js
import { sayHello } from './somefile.js';
sayHello();

// 👇 Outputs 👇
// "somefile has been loaded!"
// "Hello, world!"
Make sure to add the function to module.exports.
// somefile.js
function sayHello() {
  console.log("Hello, world!");
}

module.exports = { sayHello };

console.log("somefile has been loaded!");

Then import it

// main.js
const { sayHello } = require('./somefile.js');
sayHello();

// 👇 Outputs 👇
// "somefile has been loaded!"
// "Hello, world!"
Scope

If an exported value changes in the module it was defined in, that change is visible in all modules that import this value.

For example:
// somefile.js
let count = 1;
export { count };

setTimeout(() => count = 2, 1000);

Now use it somewhere

// main.js
import { count } from './somefile.js';

console.log(count); // 1
setTimeout(() => console.log(count), 1000); // 2

The exports are copied at the time of requiring the module.
So even if an exported value changes in the module it was defined in, that change is not visible in the module where it's required.

For example:
// somefile.js
let count = 1;
module.exports.count = count;

setTimeout(() => count = 2, 1000);

Now use it somewhere

// main.js
const mod = require('./somefile.js');

console.log(mod.count); // 1
setTimeout(() => console.log(mod.count), 1000); // 1

More examples

// somefile.js
function sayHello() {
  console.log("Hello, world!");
}

console.log("somefile has been loaded!");

Now if we just wanted to execute this file, we could do either of the following

// main.js
import './somefile.js';
// or
require('./somefile.js');

This will print "somefile has been loaded!".

Array Destructuring and Object Destructuring

Array Destructuring

let colors = ["red", "green", "blue"];

let [firstColor, secondColor] = colors;

console.log(firstColor); // "red"
console.log(secondColor); // "green"

Object Destructuring

let person = {
    name: "John Doe",
    age: 17
};

let {name, age} = person;

console.log(name); // "John Doe"
console.log(age); // 17

map and filter

map creates a new array by transforming every element of the original array.

let numbers = [1, 2, 3, 4];
let squares = numbers.map(x => x * x);
console.log(squares); // Output: [1, 4, 9, 16]

filter creates a new array by including only those elements that meet a certain condition

let numbers = [1, 2, 3, 4];
let evenNumbers = numbers.filter(x => x % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]

Comparing to LINQ in C# world

map ---> select
filter ---> where

reduce

reduce function in JS is used to apply a function to each element in an array to reduce the array to a single output value.

let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 15
  • accumulator, accumulates the return values
  • currentValue, is each value in the array
  • The value '0' after the callback function is the initial value given to the accumulator

Comparing to LINQ in C# world

var numbers = new List<int> { 1, 2, 3, 4, 5 };
int sum = numbers.Aggregate(0, (accumulator, currentValue) => accumulator + currentValue);

Console.WriteLine(sum); // Output: 15