JavaScript Definition IIII

Contents

  1. The primitive type vs Non-primitive type in JavaScript
  2. Type Coercion
  3. JavaScript is weakly typed
  4. JavaScript Function
  5. Scheme + Java
  6. TypeScript

1. The primitive type vs Non-primitive type in JavaScript

Primitive type

  • number
  • boolean
  • string
  • undefined
  • null
  • symbol

Non Primitive type (reference type)

  • type of {} (object)
  • type of [] (object)
  • type of function(){} (function)

Arrays and functions are object in JavaScript.

function a() {
    return 5;
}
a.hi = "is it object?"
console.log(a.hi);
is it object?

What is a primitive type?

const a = 5;

It is a data that only represents a single value so that means the ‘number 5’ in memory. There is no ambiguity about a variable of a primitive type directly contains the value of the type.

How about Non Primitive type?

Non Primitive type does not contain the actual value directly.

const obj = {
    name: "jay"
}
  • The obj does not contain the value directly. Instead it has a reference similar to pointer to somewhere in memory that the object.

Primitive types are immutable.

We can not really change them. In order to change them we need to completely remove the primitive type.

var a = 5;
var b = a;
b++;
console.log(a);
console.log(b);
5
6

variable a equals five. In order for me to change what that five value is i have to literally remove it from the memory and create something new a equals ten i can not really modify it just modify it just something new gets created and primitive types are exactly like that when i assign a variable a to five somewhere in memory.

However, Non primitive is mutable (reference)

let obj = {
    password: "000"
}

let new_obj = obj
new_obj.password = "chagned";

console.log(obj);
console.log(new_obj);
{ password: 'chagned' }
{ password: 'chagned' }

password has been changed both object. Object in JavaScript are stored in memory and are passed by reference which means that we do not copy the values like we did with primitive types. Thus, obj and new_obj are both pointing in memory.

So, How to copy object properly?

let c = [1, 2, 3, 4, 5];
let d = [].concat(c);
d.push(6);
console.log(c);
console.log(d);
// 2
let obj = { a: "a", b: "b", c: "c" };
let clone = Object.assign({}, obj);
obj.c = 5;
console.log(obj);
console.log(clone);
// 3
let obj1 = { a: "a1", b: "b1", c: "c1" };
let clone1 = { ...obj1 };
obj1.c = "x"
console.log(obj1);
console.log(clone1);
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5, 6 ]
{ a: 'a', b: 'b', c: 5 }
{ a: 'a', b: 'b', c: 'c' }
{ a: 'a1', b: 'b1', c: 'x' }
{ a: 'a1', b: 'b1', c: 'c1' }

However, If there is object inside object, object can not be copied perfectly.

let obj = { a: "a", b: "b", c: "c", d: { deep: "can be copied? perfectly?" } };
let clone = Object.assign({}, obj);
let clone1 = { ...obj }
clone.a = "clone-a";
clone1.b = "clone1-b";
obj.d.deep = "no";
console.log(obj);
console.log(clone);
console.log(clone1);
{ a: 'a', b: 'b', c: 'c', d: { deep: 'no' } }
{ a: 'clone-a', b: 'b', c: 'c', d: { deep: 'no' } }
{ a: 'a', b: 'clone1-b', c: 'c', d: { deep: 'no' } }

How can we deep cloning?

let obj = { a: "a", b: "b", c: "c", d: { deep: "can be copied? perfectly?" } };
let superclone = JSON.parse(JSON.stringify(obj));

obj.d.deep = "changed"
console.log(obj);
console.log(superclone);
{ a: 'a', b: 'b', c: 'c', d: { deep: 'changed' } }
{ a: 'a', b: 'b', c: 'c', d: { deep: 'can be copied? perfectly?' } }

you should be careful for using JSON.parse(JSON.stringify(());

because this can have some performance implications.

2. Type Coercion

What is type coercion?

Type coercion is the process of converting a value from one type to another type. (such as string to number). 

It is something like this one equals to string one with double equals

console.log(1 == "1");
true

That is number and string type one of them will be converted into an equivalent value by the JavaScript engine.

Do all languages have type coercion?

Yes, they do because we always need to covert types between programs to do things. In memory, different types look completely different than what we type. The number 8 in actual physical memory on the computer is represented in 1 to 0. Thus, all languages do this. It just so happens that JavaScript has an especially heavy type coercion in nature to it because it is dynamically type.

In JavaScript type coercion does not happen just with the quals sign

if (1) {
    console.log("one is true")
}

console.log(-0 === +0);
console.log(Object.is(-0, +0));
console.log(NaN === NaN);
console.log(Object.is(NaN, NaN));
one is true
true
false
false
true
  • JavaScript Type coercion one equal true.

3. JavaScript is weakly typed

JavaScript is a dynamically typed language that is weakly typed (loosely typed)

Python is a dynamically typed language that is strongly typed.

In JavaScript,

var a = "string+";
console.log(a + 7);
string+7
  • This often called type coercion in JavaScript and it can lead to some unintended consequences. This is not possible in strongly typed language like Python.

In Python,

a = "string+"
print(a+17)
TypeError: can only concatenate str (not "int") to str
Strong vs Weak typed language & Dynamic vs Static typed language

4. JavaScript Function

Many programming languages just run function to perform actions, but JavaScript can assign the function to a variable or even an object property which them become a method.

1. Function can be assign to variables and properties of the object

const a = function () {
    return null;
}

const obj = {
    a: function () {
        return null;
    }
}

2. You can pass functions as arguments into a function

function a(func){
    func()
}

a(function(){return console.log("a function as arguments")})
a function as arguments

3. You can return functions.

function a() {
    return function b(num){
        console.log(num);
    }
}

const fn = a();
fn(2)
2

More information for Initializing functions and variables inside a function.

  • Be careful of initializing functions
for (let i = 0; i < 5; i++) {
    function a() {
        return console.log("a")
    }
    a()
}

Initializing function five times

function a() { return console.log("a") }
for (let i = 0; i < 5; i++) {
    a()
}

Initializing function one time

  • Variables inside a function.
function a(){
    return x;
}

a();
ReferenceError: x is not defined

Prevent referenceError

function a() {
    if (x) {
        return x;
    }
}

a();
  • By if statement
function a(x = 3) {
    return x;
}

a();
  • With ES6 default parameter

5. Scheme + Java

In 1995, Brendan Eich released JavaScript he was inspired by two languages which are Scheme and Java. Scheme was a programming language that was created at MIT in the 70s. It was a very quiet unique language that has a closure in the program. And then Java at the time that JavaScript was created was the trendiest language.

The idea of object-oriented programming where objects where the Key to building programs.

The idea of Scheme where functions where the key to building programs.

The roots of JavaScript which were inspired by Scheme and Java. so JavaScript has the multi-paradigm language.

6. TypeScript

TypeScript is an open-source language that builds on JavaScript, one of the world’s most used tools, by adding static type definitions. And typescript is a superset of javascript.

There are a ton of programming languages. Although JavaScript is the dominant language on the web.

In JavaScript,

var a = 100;

You see a dynamically typed language allows us to not have to say what type of variable.

In C++

int a;
a = 100;

A statically typed language like c++ we have to declare type of a variable.

Dynamically typed languages, type checking is done during runtime.

We are able to use dynamic typed languages that can assign anything to any variable and you are not going to be caught. You might get errors during runtime while users browsing the web.

  • some people think statically typed languages are the way to go.
  • some people think statically typed languages are a waste of time.

TypeScript Pros and Cons

Pros

  1. Statically typed languages are self documenting.
function sum(a: number, b: number) {
    return a + b;
}
sum("hello", 5)
  • string is not assignable to parameter of type ‘number’.

2. Many IDE help with auto completion.

3. The main thing of statically typed languages is that you are going to get less bugs in production.

Cons

  1. You just made our code a little bit harder to read and complex.
  2. You just need to write better tests.
    1. Many people get excited about static typing and skip writing a test.
  3. You are going to have a slower development process because you now have extra steps.
  • The main thing static types usually prevent bugs and help keep errors from happening dynamic typing allows you to be more flexible and write software faster.
  • TypeScript allows us to make JavaScript behave like a statically typed language it adds types to JavaScript.

Install TypeScript via npm

$ npm install -g typescript
$ tsc -version
Version 4.0.3

Execute TypeScript

  1. Convert TS file to JS file and execute
$ tsc main.ts && node main.js

2. Use ts-node

$ npm install -g ts-node
$ ts-node main.ts

Leave a Reply

Your email address will not be published.

ANOTE.DEV