Javascript / Node.js : 8 simple single style code declaration for javascript newcomer to focused on

Jethro David
Nov 5, 2018 · 7 min read

Unlike other strict programmer languages like Golang, or C#, there’s a lot way to do things with javascript style code. This brings confusion to who’s not yet familiar into dynamic typing language like javascript. There’s a lot of changes lately at javascript ECMAScript. This will bring more creativity to who's familiar with, and chaos to who's not familiar in this Continent.

I create this single style javascript code declaration and I think it’s essential to them who's willing to move in this programming language. I’m sure when you understand all of this 8 single style of code declaration, you can help you faster make a software.

In the meantime, you’ll learn the other style who’s more efficient based on the logic you’re handling on. So I hope this article will help you find the consistency in javascript declaration style.


prerequisite

node v 8.0.0 or more

1. Javascript data types (Easy)

// Boolean
typeof true // "boolean"
// null
typeof null // "object"
// undefined
typeof undefined // "undefined"
// double-precision 64-bit binary format IEEE 754 value
// number between -(253^-1) and 253^-1)
typeof -4000.125 // "number"
typeof 4000/0 // NaN
typeof NaN // "number"
// string
typeof 'hello World' // "string"
typeof '4000.23' // "string"
// object
typeof {name: 'Jenifer', age: 23} // "object"
// array
typeof [1, 2, 3] // "object"
// date
typeof new Date() // "object"

2. Function declaration (Easy)

0–3 parameters

const joinFullName = (firstName, middleName, lastName)=>{
return `${firstName}, ${middleName}, ${lastName}`;
}
const result = joinFullName('Jenifer', 'Viking', 'Lawrance');
console.log(result); //==> Jenifer, Viking, Lawrance

4 parameters or more

const introduction = ({name, age, relationship, job}) =>{ 
return `Hi my name is ${name}, I'm ${age} years old. My relationship status is ${relationship}. I'm working at ${job}. Thank you.`
}
const myIntroduction = introduction({
name: 'Jenifer Lawrance',
age: 23,
relationship: 'Single',
job: 'Public Figure',
});
console.log(myIntroduction);

3. Exporting & Importing Module (Medium)

exporting single modules

// helpers/getFullName.js
module.exports = (firstName, lastName)=>{
return `${firstName} ${lastName}`;
}
// helpers/getDate.js
module.exports = ()=>{
return new Date();
}

joining multiple single modules

// helpers/index.js
const getFullName = require('./getFullName');
const getDate = require('./getDate');
module.exports = {
getFullName,
getDate,
};

multiple modules

// personModule.js
module.exports = {
greeting :(name)=>{
console.log(`Hello ${name}`);
},
introduction: (name, age)=>{
console.log(`Hello my name is ${name}, age ${age}`);
},
}

Importing modules

// Single Module
const fullname = require('./helpers/getFullName');
const date = require('./helpers/getDate');
console.log(fullname('John', 'Cenna'));
console.log(date());
// Joinned Single modules
const {getFullName, getDate}= require('./helpers');
console.log(getFullName('John', 'Cenna'));
console.log(getDate());
// multiple modules
const {greeting, introduction}= require('./personModule');
greeting('Jenifer');
introduction('Jenifer', 23);

Private(un-exported) & Public(exported) Function

// personModule.js// Private Function
const getDate = ()=>{
return new Date()
}
// Public Function
module.exports = {
greeting :(name)=>{
console.log(`Hello ${name}`);
},
introduction: (name, age)=>{
console.log(`
Hello my name is ${name}, age ${age},
today is ${getDate()}. have a Nice Day :D
`);
},
}

4. Variable declaration with var, let, const, this (Easy)

// var !!NEVER USE VAR!!
var x = 1;
if (x === 1) {
var x = 2;
console.log(x); // expected output: 2, real output: 2
}
console.log(x);
// expected output: 1
// real output: 2

// let
let x = 1;
if (x === 1) {
let x = 2;
console.log(x); // expected output: 2, real output: 2
}
console.log(x);
// expected output: 1
// real output: 1
// Const
const a = 'hello';
a = ' World';
console.log(a); // program will break
// We can alter array as long it's not assigned
const listNumber = [1, 2];
listNumber.push(3);
console.log(listNumber); // [1, 2, 3]
// We can assign object properties
const person = {
name: 'Jenifer',
age: 23,
};
person.name= 'Jenifer Syantik ';
person.lastName = ' Lawrance';
console.log(person);
// expected output
// { name: 'Jenifer Syantik ', age: 23, lastName: ' Lawrance' }
// this
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(person.fullName());

please learn more about this in this link Important

5. Array & Object (Easy)

// looping an array
const personList = [
{
name: 'Jenifer',
lastName: 'Lawrance'
},
{
name: 'Taylor',
lastName: 'Swift'
},
];
const personWithFullName = [];personList.forEach((item, index, list) => {
list[index].fullName = `${item.name} ${item.lastName}`;
personWithFullName.push({
sequence: index + 1,
fullName: `${item.name} ${item.lastName}`,
});
});
console.log({ personList });
console.log({ personWithFullName });

// Looping an object
const listInObject ={
1002: {name:'Jenifer'},
1003: {name:'Selena',}
};
console.log(Object.keys(listInObject));Object.keys(listInObject).forEach((item) => {
listInObject[item].age = 23;
});
console.log(listInObject);

6. Callback & Promise (Hard)

Callback

const isEvenNumber = (numberInput, successCB, errorCB) => { 
setTimeout(() => {
if (typeof numberInput !== 'number') {
errorCB(new Error('input is not number'));
return false;
}
if (numberInput % 2 !== 0) {
successCB('ODD Number');
return true;
}
successCB('EVEN Number');
return true;
}, 2000);
};
isEvenNumber('foo', (result) => {
console.log(result);
}, (error) => {
console.error(error);
});// expected result: input is not number;
isEvenNumber(9, (result) => {
console.log(result);
}, (error) => {
console.error(error);
});// expected result: ODD Number
isEvenNumber(8, (result) => {
console.log(result);
}, (error) => {
console.error(error);
});// expected result: EVEN Number

Promise

const isOddNumber = (numberInput) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (typeof numberInput !== 'number') {
reject(new Error('input is not number'));
return false;
}
if (numberInput % 2 === 0) {
resolve('EVEN Number');
return true;
}
resolve('ODD Number');
return true;
}, 2000);
});
};
isOddNumber('foo')
.then((result) => {
console.log(result);
}).catch((error) => {
console.error(error);
});// expected result: input is not number;
isOddNumber('foo')
.then((result) => {
console.log(result);
}).catch((error) => {
console.error(error);
});// expected result: EVEN Number
isOddNumber('foo')
.then((result) => {
console.log(result);
}).catch((error) => {
console.error(error);
});// expected result: ODD Number

7. Async Await (Medium)

given 2 API Promise functions

const getBookList = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([
{
id: 1,
title: '12 Rules for Life',
author_id: 13,
},
{
id: 2,
title: '7 Habbits',
author_id: 11,
},
{
id: 3,
title: 'Positive Thingking',
author_id: 12,
},
{
id: 4,
title: 'Elon Musk',
author_id: 14,
},
]);
}, 2000);
});
};
const getAuthorList = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([
{
id: 11,
title: 'Steven R Covey',
books_id: [2],
},
{
id: 12,
title: 'Norman Vincent Peale',
books_id: [3],
},
{
id: 13,
title: 'Jordan B Peterson',
books_id: [4],
},
{
id: 14,
title: 'Ashlee Vance',
books_id: [4],
},
]);
}, 2000);
});
};

Serial Call

const serialCall = async () => {
console.time('serialCallTime');
let i = 0;
while (i < 100000) { i += 1; }
try {
const bookResponse = await getBookList();
const authorResponse = await getAuthorList();
console.timeEnd('serialCallTime');
console.log({ bookResponse, authorResponse });
} catch (error) {
console.timeEnd('serialCallTime');
console.error(error);
}
};
serialCall();
// serialCallTime: 4012.267ms

Parallel Call

const ParallelCall = async () => {
console.time('ParallelCallTime');
let i = 0;
while (i < 100000) { i += 1; }
try {
const responseArray = await Promise.all([
getBookList(),
getAuthorList(),
]);
const bookResponse = responseArray[0];
const authorResponse = responseArray[1];
console.timeEnd('ParallelCallTime');
console.log({ bookResponse, authorResponse });
} catch (error) {
console.timeEnd('ParallelCallTime');
console.error(error);
}
};
ParallelCall();
// ParallelCallTime: 2003.718ms

8. Mutable & Immutable Object (Hard)

When passing an object or array into a new variable, it’s not a new value created, instead booth value inside variable will be referenced to the same memory address. Every changes on a variable, will be affected on booth variable where they got referenced from (Mutable).

If you want the first variable isn’t mutable (Immutable), you should create/assign a new object, or deepClone that object/array, I always recomend using JSON.parse(JSON.stringify(variable)) to deepclone an object, so the original object is immutable.

Object example

const a = {
foo: 'bar'
};
const b = a;
a.foo = 'test';
console.log(b.foo); // test
console.log(a === b); // true
b.bar = 'test bar';console.log(a.bar); // test bar
console.log(a === b); // true
const c = JSON.parse(JSON.stringify(a)); //deepClone
c.foo = 'cc gg'; // changes in c will not mutate the a
console.log(a.foo); // test
console.log(c.foo); // cc gg
console.log(a === c); // false

Array example

const a = ['foo', 'bar'];
const b = a;
a.push('baz');
console.log(b); // ['foo', 'bar', 'baz']
console.log(a === b); // true
b.push('bizz');console.log(a); // ['foo', 'bar', 'baz', 'bizz']
console.log(a === b); // true
const c = JSON.parse(JSON.stringify(a)); //deepClone
c.push('cc gg'); // changes in c will not mutate the a
console.log(a); // ['foo', 'bar', 'baz', 'bizz']
console.log(c); // ['foo', 'bar', 'baz', 'bizz', 'cc gg']
console.log(a === c); // false

Original Non object / Non Array variable is always immutable

let a = 1;
let b = a;
a += 1;

console.log(a); // 2
console.log(b); // 1
console.log(a === b); // false
let c = 'foo';
let d = c;
d = 'bar';
console.log(c); // "foo"
console.log(d); // "bar"
console.log(c === b); // false

Real world example mutable is useful.

const assignAuthors = (input)=>{
//no need return. this is usefull if you need to
//mapping the deep children array
input.authorName = 'Stephen R Covey';
};
const book = {
id: 1,
title: '7 Habbits',
author_id: 11,
};
assignAuthors(book);
console.log(book);
/*
{
id: 1,
title: '7 Habbits',
author_id: 11,
authorName: 'Stephen R Covey',
}
*/

Ready to make a software? I think those 8 are enough to start with node.js, good luck, have fun… :D

In the meantime, if you’re looking for a detailed concept (it will slow you down to ship the software tough). I recommend you yo read this books .
https://github.com/getify/You-Dont-Know-JS

Cheers…

Jethro David

Written by

INTJ... I have a lot idea in my mind. In progress to make it happen. learning the hard skill to make best concept of it, and soft skill to present it well

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade