A thread of tips, lessons, gotchas, syntactical conventions, semantics, structures and common errors regarding JavaScript.
Follow to be enlightened!
#100DaysofCode
#Javascript
#CodeNewbies
Follow to be enlightened!
#100DaysofCode
#Javascript
#CodeNewbies
1: All programming languages works with data, and there are 7 built in data types in #JavaScript:
β’ null
β’ undefined
β’ boolean
β’ number
β’ string
β’ object
β’ symbolβadded in ES6!
They are also called primitive types
#100DaysOfCode
#CodeNewbies
β’ null
β’ undefined
β’ boolean
β’ number
β’ string
β’ object
β’ symbolβadded in ES6!
They are also called primitive types
#100DaysOfCode
#CodeNewbies
2: #null essentially means "no data", empty, nada. #undefined means data has not been explicitly defined or declared. #boolean evaluates to either true or false. #numbers are digits between 0-9, #strings are characters enclosed within double quotes
#100DaysOfCode
#CodeNewbie
#100DaysOfCode
#CodeNewbie
3: Data is held in a container called a variable. The name of the variable is called an identifier as it "identifies" data. Variables in #javascript can be:
#const - block scoped and fixed
#let - block scoped and reassignable
#var - global
#100DaysOfCode
#CodeNewbie
#const - block scoped and fixed
#let - block scoped and reassignable
#var - global
#100DaysOfCode
#CodeNewbie
4: You assign data (value) to a variable using the assignment operator (=):
let holder = "data" //assigns string value to variable
const PI = 3.14 // assigns number value to variable
You can access variables depending on type of declaration used
#100DaysOfCode
#CodeNewbies
let holder = "data" //assigns string value to variable
const PI = 3.14 // assigns number value to variable
You can access variables depending on type of declaration used
#100DaysOfCode
#CodeNewbies
5: #typeof operator is used to inspect the data type of the value assigned to a variable:
var phone_no = 0577464778 ;
var title = "Moon shining";
typeof phone_no //number
typeof title //string
#100DaysOfCode
#CodeNewbie
var phone_no = 0577464778 ;
var title = "Moon shining";
typeof phone_no //number
typeof title //string
#100DaysOfCode
#CodeNewbie
6: An object is a data structure whose properties are represented by a key: value pair. Built-in objects, like String, can be created via a constructor call:
new String(lmao)
Object literal style: {}
Object properties describes things about your object
#100DaysOfCode
new String(lmao)
Object literal style: {}
Object properties describes things about your object
#100DaysOfCode
7: An #Array is a data structure in which data is represented/referred to by indices. First item in an Array has an index value of 0, and so on. Arrays can be created via a constructor call or literal method - [ ].
var My_array = [car, mat, dog]
#100DaysOfCode
#CodeNewbie
var My_array = [car, mat, dog]
#100DaysOfCode
#CodeNewbie
8: A #function is a callable object i.e it can be called to perform an action. Functions optionally take in data as parameters, works on the data, and optionally returns a value.
Function addNums (n1, n2) {
return n1 * n2 ;
}
addNums (1, 2); // 3
#100DaysOfCode
#CodeNewbie
Function addNums (n1, n2) {
return n1 * n2 ;
}
addNums (1, 2); // 3
#100DaysOfCode
#CodeNewbie
9:Every expression in JS can be evaluated down to a single, specific value result:
var a = 3 * 6;
var b = a;
b;
3 * 6 is an expression (evaluates to the value 18), so is a and b. b = a is an assignment expression. var is a declaration statement
#100DaysOfCode
#CodeNewbies
var a = 3 * 6;
var b = a;
b;
3 * 6 is an expression (evaluates to the value 18), so is a and b. b = a is an assignment expression. var is a declaration statement
#100DaysOfCode
#CodeNewbies
10: You can access the properties of an object with the dot notation:
var car = {name: audi,
color: blue,
price: 500,
models: { sport: 2007,
convertible: 2013},
}
access the color & sport property of car:
car.color // blue
http://car.model.sport // 2017
#100DaysOfCode
var car = {name: audi,
color: blue,
price: 500,
models: { sport: 2007,
convertible: 2013},
}
access the color & sport property of car:
car.color // blue
http://car.model.sport // 2017
#100DaysOfCode
11: You can access the elements in an array like this:
A[index] - A is the name of the array, index is the numerical position of the element starting from 0.
var Evens = [2,4,6,8,10]
Evens[0]; // 2
Evens[2]; //6
#100DaysOfCode
#CodeNewbie
#JavaScriptmas
A[index] - A is the name of the array, index is the numerical position of the element starting from 0.
var Evens = [2,4,6,8,10]
Evens[0]; // 2
Evens[2]; //6
#100DaysOfCode
#CodeNewbie
#JavaScriptmas
12: You extract properties from an object via a process known as object destructuring:
var book =
{ name: demented,
color: red,
price: 199 }
var {name, color} = book;
name; //demented
color; // red
#100DaysOfCode
#CodeNewbies
#JavaScriptmas
var book =
{ name: demented,
color: red,
price: 199 }
var {name, color} = book;
name; //demented
color; // red
#100DaysOfCode
#CodeNewbies
#JavaScriptmas
13: #Asynchrony is simply a situation in which part of a program executes now and the other runs at a later time. Normally, a program is executed step-by-step, line-by-line. However, when asynchrony is introduced, the async code is skipped and will run later.
#100DaysOfCode
#100DaysOfCode
14: A callback function is the unit of asynchrony; it shows there is a later part in your code:
function add (a, b, cB) {
return cB(a+b) ;
}
add(1, 2, function (c) {
console.log(c);
}) // 3
They're functions inside another function
#100DaysOfCode
#CodeNewbie
#JavaScript
function add (a, b, cB) {
return cB(a+b) ;
}
add(1, 2, function (c) {
console.log(c);
}) // 3
They're functions inside another function
#100DaysOfCode
#CodeNewbie
#JavaScript
concat()
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
lastIndexOf()
map()
pop()
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
#100DaysOfCode
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
lastIndexOf()
map()
pop()
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
#100DaysOfCode
15: Some of the aforementioned array methods can mutate items.
splice(): Adds/Removes elements from an array
toString():Converts an array to a string
unshift(): Adds new elements to the beginning of an array, returns the new length
Mutation can be problematic
#100DaysOfCode
splice(): Adds/Removes elements from an array
toString():Converts an array to a string
unshift(): Adds new elements to the beginning of an array, returns the new length
Mutation can be problematic
#100DaysOfCode
16: To avoid mutation, you can use an array method that doesn't mutate or better yet, use a spread operator (...):
const verbs = [run, slap, eat]
const moreVerbs = [kill, sit, .
..verbs]
With it, you can clone an array or object and mutate it.
#100DaysOfCode
#CodeNewbie
const verbs = [run, slap, eat]
const moreVerbs = [kill, sit, .
..verbs]
With it, you can clone an array or object and mutate it.
#100DaysOfCode
#CodeNewbie
17: You can also spread an object into another object:
const myAlphanums = { c: 3, d: 4 }
const moreAlphanums = { a: 1, b: 2, ... myAlphanums }
// {a: 1, b: 2, c: 3, d: 4,}
N/B: spread operators preserves order in the new array/object.
#100DaysOfCode
#CodeNewbie
const myAlphanums = { c: 3, d: 4 }
const moreAlphanums = { a: 1, b: 2, ... myAlphanums }
// {a: 1, b: 2, c: 3, d: 4,}
N/B: spread operators preserves order in the new array/object.
#100DaysOfCode
#CodeNewbie
18: var evens = [2, 4, 6, 8]
You can iterate over the elements of an array, performing a consistent action to each item, with a for loop
for (const i = 0, i = evens.length, i++) {
return evens[i] * 2 ;
}
the i = 0 expression is evaluated before the code runs.
#100DaysOfCode
You can iterate over the elements of an array, performing a consistent action to each item, with a for loop
for (const i = 0, i = evens.length, i++) {
return evens[i] * 2 ;
}
the i = 0 expression is evaluated before the code runs.
#100DaysOfCode
19: you can also repeatedly execute some instruction while a condition is true, using the while loop:
let a = 1
while (a < 5) {
console.log(a);
a++;
}
//1,2,3,4
Don't forget to increment the variable on every iteration so it doesn't run forever.
#100DaysOfCode
#CodeNewbie
let a = 1
while (a < 5) {
console.log(a);
a++;
}
//1,2,3,4
Don't forget to increment the variable on every iteration so it doesn't run forever.
#100DaysOfCode
#CodeNewbie
20: The do/while loop is a variant of the while loop. Only that this loop will always be executed at least once, even if the condition is false, cuz the block is executed before the condition is tested:
var i = 0;
do {
console.log(i)
i++;
}
while (i < 5);
#100DaysOfCode
var i = 0;
do {
console.log(i)
i++;
}
while (i < 5);
#100DaysOfCode
21: You can iterate over the KEYS of an object using a for/in loop:
var profile = {fname:"John", lname:"Doe", age:45};
var text = "";
var v;
for (v in profile) {
text += profile[v];
}
N/B: You'll have reference the object's values in the block.
#100DaysOfCode
#CodeNew
var profile = {fname:"John", lname:"Doe", age:45};
var text = "";
var v;
for (v in profile) {
text += profile[v];
}
N/B: You'll have reference the object's values in the block.
#100DaysOfCode
#CodeNew
22: You iterate over the VALUES of an object using the for/of loop:
var car = {name: "BMW", color: "red", model: 2005};
var x;
for (v of car) {
document.write(v + "<br >");
}
//BMW
red
2005
#100DaysOfCode
#CodeNewbie
var car = {name: "BMW", color: "red", model: 2005};
var x;
for (v of car) {
document.write(v + "<br >");
}
//BMW
red
2005
#100DaysOfCode
#CodeNewbie
23: Like Objects and Arrays, a Map is a collection for storing data. Ideal when frequently adding and removing items.
let car = new Map()
.set('name', 'Audi')
.set('size', 'large')
.set('color', 'red');
car.get('color'); // 'red'
car.delete('color') //deleted
#100DaysOfCode
let car = new Map()
.set('name', 'Audi')
.set('size', 'large')
.set('color', 'red');
car.get('color'); // 'red'
car.delete('color') //deleted
#100DaysOfCode
24: A set is used to store unique values. Use has() to check for a value, delete() to clear property, clear() to clear.
let names = new Set();
names.add('joe');
// Set { 'joe'}
names.add('poe');
// Set { 'joe', 'poe'}
names.add('poe');
// Set { 'joe', 'poe'}
#100DaysOfCode
let names = new Set();
names.add('joe');
// Set { 'joe'}
names.add('poe');
// Set { 'joe', 'poe'}
names.add('poe');
// Set { 'joe', 'poe'}
#100DaysOfCode
25: Built-in functions for constructing objects:
β’ String
β’ Number
β’ Boolean
β’ Object
β’ Function
β’ Array
β’ Date
β’ RegExp
β’ Error
See the next tweet
#100DaysOfCode
#CodeNewbie
β’ String
β’ Number
β’ Boolean
β’ Object
β’ Function
β’ Array
β’ Date
β’ RegExp
β’ Error
See the next tweet
#100DaysOfCode
#CodeNewbie
Each of the built-in functions can be used as a constructor, the result being a newly constructed object of d subtype in question.
var strPrimitive = "I am a string";
typeof strPrimitive; // "string"
var strObject = new String( "I am a string" );
typeof strObject; // "object"
var strPrimitive = "I am a string";
typeof strPrimitive; // "string"
var strObject = new String( "I am a string" );
typeof strObject; // "object"
26: You can explicitly coerce between the two data types:
var a = 42;
var b = String( a );
var c = "3.14";
var d = Number( c );
b; // "42"
d; // 3.14
variable a is coerced into a string and c is coerced into a number.
#100DaysOfCode
#CodeNewbie
var a = 42;
var b = String( a );
var c = "3.14";
var d = Number( c );
b; // "42"
d; // 3.14
variable a is coerced into a string and c is coerced into a number.
#100DaysOfCode
#CodeNewbie
27: Built-in array iterator methods are functions which on every iteration takes in a new item in an array and calls a callback fn on that item. It stops when all items are iterated over or a given condition is met.
They are similar to the for() index loop.
#100DaysOfCode
They are similar to the for() index loop.
#100DaysOfCode
28: One of them is map(). Here is what it does:
const teams = [
{ name: "Man U",
points: 40 },
{name: "Arsenal"
points: 32}
]
var newT= teams .map(team => { team.points + 3 })
// [
{ name: "Man U",
points: 43 },
{name: "Arsenal"
points: 35}
#100DaysOfCode
const teams = [
{ name: "Man U",
points: 40 },
{name: "Arsenal"
points: 32}
]
var newT= teams .map(team => { team.points + 3 })
// [
{ name: "Man U",
points: 43 },
{name: "Arsenal"
points: 35}
#100DaysOfCode
29: Another is filter():
const teams = [
{ name: "Man U",
points: 40 },
{name: "Arsenal"
points: 38},
{name: "Spurs"
points: 35}
]
var NewT = teams .filter(team=> team.points > 36);
// [
{ name: "Man U",
points: 40 },
{name: "Arsenal"
points: 38}
]
#100DaysOfCode
const teams = [
{ name: "Man U",
points: 40 },
{name: "Arsenal"
points: 38},
{name: "Spurs"
points: 35}
]
var NewT = teams .filter(team=> team.points > 36);
// [
{ name: "Man U",
points: 40 },
{name: "Arsenal"
points: 38}
]
#100DaysOfCode
30: Find(). Returns only d 1st instance that evaluates to true:
const ppl = [
{
name: 'Jim',
status: ['Married'],
},
{
name: 'Anna',
status: ['Married', 'Parent'],
},
{
name: 'Ed',
status: ['Married''],
},
];
const prnt = ppl.find(person =>person.status.includes('Parent''));
const ppl = [
{
name: 'Jim',
status: ['Married'],
},
{
name: 'Anna',
status: ['Married', 'Parent'],
},
{
name: 'Ed',
status: ['Married''],
},
];
const prnt = ppl.find(person =>person.status.includes('Parent''));
31: We also have forEach(). Unlike other array iterator methods, this one doesn't return an array of anything
const names = ['mark', 'jane'];
let capitalized = [];
names.forEach(name => capitalized.push(name.toUpperCase()));
capitalized;
// ['MARK', 'JANE'];
#100DaysOfCode
const names = ['mark', 'jane'];
let capitalized = [];
names.forEach(name => capitalized.push(name.toUpperCase()));
capitalized;
// ['MARK', 'JANE'];
#100DaysOfCode