[Go to site: main page, start]

0% found this document useful (0 votes)
8 views19 pages

JavaScript Basics: Variables & Data Types

The document provides an overview of JavaScript fundamentals, including data types, variable declarations, and operations. It covers concepts such as variable scope, functions, arrays, and conditional logic, along with examples of syntax and usage. Additionally, it explains the importance of operators and control structures in programming with JavaScript.

Uploaded by

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

JavaScript Basics: Variables & Data Types

The document provides an overview of JavaScript fundamentals, including data types, variable declarations, and operations. It covers concepts such as variable scope, functions, arrays, and conditional logic, along with examples of syntax and usage. Additionally, it explains the importance of operators and control structures in programming with JavaScript.

Uploaded by

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

14Aug2021 console.

log (value)– it is to check what happened


to the variables, like a print command
JavaScript from FCC by Beau Carnes

// - create comments Initialize variable – variable with value at the start


/* -starts */-ends with – to create multiline Uninitialized variable – variable without value at
comments in a javascript code the start

Always end a line with a semicolon Variables are case sensitive in JavaScript

7 Data Types and Variables in JavaScript var studly is NOT THE SAME with var STUDLY

Undefined – variable not set to anything yet Addition


Null – variable set to be something but doesn’t var sum = 1+0;
hold any value [Link](sum);
Boolean – True or false variable  1
String – any text; they are immutable
Symbol – immutable value that is unique Subtraction
Number – a number Var difference = 2-1;
Object – store a lot of different key value pairs [Link](difference);
 1
Variable
- It is like a box that fills something that you Product
want Var product = 8*10;
- Use of a var or let or const keyword [Link](product);
- Var – the variable will be set for use all  80
throughout the program
- Let – variable that will only be used of Division
where it was declared Var product = 8/2;
- Const – variable that should NEVER change [Link](division);
- Example in assigning:  4
o var myName = “Troyss”
o let myName = 8 Increment 1
o const pi = “Troyss” myvar = 11;
myvar = ++;
Declaring vs. Assigning variables [Link](myvar);
 12
Assigning variables – assign variables
Examples: Decrement 1
myvar = 11;
var a; // declaring a variable myvar = ++;
[Link](myvar);
Var b = 2; //assigning of a variable  10

a = 7; // assigning of variable example Decimals or Floats

var myDecimal = 0.009;


1
Declaring string variables
multiplying decimals or floats would have the same
as integers var name = “Troyss”;

var product = 2.0 * 2.5; To assign literal quotes in a string:


[Link](product); Example:
 5
var name = “This is a double quote\”\” “
var quotient = 4.4/2.0;
[Link](quotient); put a backslash for the quotes in a string
 2.2
A string can be surrounded by either double quotes
For remainders or single quotes

var remainder; Use of single quotes can identify double quotes in a


remainder = 11%3; string as part of the variable, while the use of the
[Link] (remainder); other allows vice versa
 2
Use of backticks ( ` ) can allow the string to identify
Compound assignment double quote or single quotes as part of the string

var a = 11
Commands
Instead of a = 9+a;
You can do: \’ single quote
a += 9; \” double quote
[Link](a); \\ backslash
 20 \n newline
\r carriage return
Instead of a =a-6; \t tab
You can do: \b backspace
a-=6 \f form feed
[Link](a);
 5
Example:
Instead of a = a*5; var Troyss = “1stLine\n\t\\2ndLine\nThirdLine”;
You can do: [Link](Troyss);
a *= 5;  1stLine
[Link](a) 2ndLine
 55 ThirdLine

Instead of a = a/11; Concatenate strings with + operator


You can do:
a /= 11; var ourStr = “Troyss” + “ “ + “Pilapil”;
[Link](a); [Link](ourStr);
 1  Troyss Pilapil

2
It is also possible to:  o
var ourStr = “1st”;
ourStr += “2nd”; [ ] – bracket notation
[Link] (ourStr);
 1st2nd var str = "Bello";
str [0] = "H";
Constructing Strings with variables [Link](str);
 “Bello”
var 1stName = “Troyss”
var 2ndName = “Pilapil” - String is immutable, so changing the string
based on position cannot be put into effect
var TotalName = “My name is” + “ “ + 1stName + “
“ + 2ndName; To fix that to “Hello”:
[Link](TotalName);
 My name is Troyss Pilapil var str = "Bello";
str = “Hello”;
It is also possible: [Link](str);
 “Hello”
var good = “Yes”;
var bad = “No”; To find last character in the string

var good+=bad; var name = “Troyss”;


[Link](good); var namelength = name[[Link] -1];
 YesNo [Link](namelength);
 “s”

Finding length of string To find the nth last character in the string

var firstname = “Troyss” var name = “Troyss”;


firstnamelength = [Link]; var namelength = name[[Link] -3];
[Link](firstnamelength); [Link](namelength);
 6  “y”

Bracket notation to look for the character in a Word blanks


string
- Assigning values to variables in same ordinal
Computers do zero-based indexing, the count positions
starts at zero, NOT 1 - Example:

var firstname = “Troyss” Function wordBlanks (myNoun, myAdjective,


firstname1stletter = firstname[0]; myVerb, myAdverb) {
[Link](firstname1stletter);
 T var result = “”;

var firstname = “Troyss” result += “The “ + myAdjective + “ “ myNoun + “ “ +


firstname1stletter = firstname[2]; myVerb + “ to the store “ + myAdverb
[Link](firstname1stletter);
3
return result;
} Use of a PUSH function

[Link] (wordBlanks(“dog”, “big, “ran”, - Used to add a value to an array


“quickly” ));
 The big dog ran to the store quickly var anArray = [“Troyss”, “Pilapil”];
[Link]([“Mikee”]);
[Link] (wordBlanks(“bike”, “slow”, “flew”, [Link](anArray);
“slowly”));  Troyss Pilapil Mikee
 The slow bike flew to the store slowly
Use of a POP function
Storing multiple value in arrays - Removal of a value from an array

var anArray = [“Troyss”, 2]; var anArray = [“Troyss”, “Pilapil”];


var shortArray = [Link]();
Nested array is an array within another array [Link](shortArray);
 Troyss
Example:
var anArray = [[“Troyss”, “groom”], [“Mikee”, Manipulate Arrays with shift
“bride”]];
- Same with POP function but instead goes to
Indexing of arrays the opposite direction. Instead of last,
removes the first value
var anArray = [50, 60, 70];
var mydata = anArray [0]; var anArray = [“Troyss”, “Pilapil”];
[Link] (mydata); var shortArray = [Link]();
 50 [Link](shortArray);
 Pilapil
Modifying arrays

var anArray = [50, 60, 70]; Manipulate Arrays with unshift


anArray [1] = 45;
[Link] (anArray); - Same with PUSH function but instead goes
 50, 45, 70 to the opposite direction. Instead of last,
adds before the first value
Modifying multidimensional arrays
var anArray = [“Troyss”, “Pilapil”];
- To access multiple arrays in a multilevel var shortArray = [Link](“Mikee”);
arrays using multiple bracketing [Link](shortArray);
-  Mikee, Troyss, Pilapil

var anArray = [[1,2,3], [4,5,6], [7,8,9],[[10,11,12],


13, 14]; Writing reusable codes
var mydata = anArray [2][1];
[Link] (myData); Functions – reusable codes for all the programs
 8
Example:
4
Return a value from a function
function Troyss() {
[Link](“Hello World”!); Produce a result froma. Function
}
function operation (num){
Troyss(); return num -7;
}
[Link](operation(10);
 3
Passing values to functions
Understanding undefined value returned from a
function EXargs(a,b){ function
[Link](a-b);
} var sum = 0;
function addThree(){
EXargs(10,5); sum = sum + 3;
}
Global Scope and Functions [Link](addThree());
 Undefined
Scope refers to the visibility of variables
Code needs “return sum” to create the result
Variables which are defined outside of a function
block have global scope
Assignment with a returned value
Global scope means functions can be seen all
through the Javascript code var sample= 0;
function sample1(num){
!= - refers to NOT EQUAL return (num+5)/3;
}
sample = sample1(10);
Local Scope and functions [Link] (sample);
 5
- Declaration of a variable inside a function
and thus only be readable inside a function Stand in Line

function myLocal(){ Cue is an abstract data structure where items are


var myVar = 5; kept in order
[Link](myVar);
} function lining(arr, item){
myLocal(); [Link](item);
[Link](myVar); return [Link]();
 5 }
 Error
var testArr = [1,2,3,4,5];
Error because myVar can’t be accessed inside the
function as it was declared in a local scope [Link](“Before: “ +[Link](testArr));
[Link](lining(testArr,6));
5
[Link](“After: “ + [Link](testArr)); For example:
 Before: [1,2,3,4,5] 12 != 11 is true, or 12 != 12 is false
 1 12 != “11” is true
 After: [2,3,4,5,6]

!== - the not equal sign


[Link] - command to convert the array to It also does type conversion
string For example:
12 != 11 is true, or 12 != 12 is false
12 != “11” is FALSE

Booleans
> - Greater than
Data type in JavaScript that can only hold two It also does not do type conversion
values, true or false For example:
12 > 11 is true, or 12 > 12 is false
Does not need quotation marks for true and false 12 > “11” is true

Use of conditional logic if statements >= - Greater than or equal to


It also does not do type conversion
If statements are used to make decisions in code. If For example:
tells JS to execute code based on the defined 12 >= 11 is true, or 12 >= 12 is true
conditions 12 > “11” is true, 12 >= 10 is false
“If (condition)”
< - Less than
function Question(isitTrue){ It also does not do type conversion
if (isitTrue){ For example:
return “Yes, it’s true”; 12 < 11 is false, or 12 < 12 is false
} 12 < “11” is false, 12 < 13 is true
Return “No, it’s false”;
} <= - Greater than or equal to
It also does not do type conversion
Operators For example:
== - equality operator 12 <= 11 is false, or 12 <= 12 is true
Evaluates with the equal type conversion 12 < “11” is false, 12 <= 13 is true
For example:
12 == 12 is true, or 12 == 11 is false && - AND operator
12 == “12” is true Used to check to fulfill both statements

=== - strict operator equality function testlogic(val){


Evaluates the value including the type if (val <= 50 && val >= 25) {
For example: return “Yes”;
12 === 12 is true, or 12 === 11 is false }
12 === “12” is FALSE Return “No”;
}
!= - the not equal sign testlogic(10);
It also does not do type conversion  No
6
Testlogic(30);  Between 40 to 50
 Yes
Logical order of Else If statements
|| - OR operator
Used to check to fulfill one of the statements Else if statements run it in a logical sequence and if
function testlogic(val){ it is accepted in the first statement, it will be
if (val >= 50 || val <= 25) { running on the accepted condition.
return “Yes”;
} Tip: to make it work, prioritize smallest values and
Return “No”; code towards larger values at the end of if
} statements
testlogic(10);
 Yes
Testlogic(30);
 No Switch statement

Else Switch statement tests a value and can have many


-statements used to be added to commands that case statement which define various possible
does not fulfill the set execution values

function testlogic(val){ Case is like -> “If === (the value)”


if (val >= 50) {
return “Yes”; function caseSwitch (val){
} else { var answer = “”;
Return “No”; switch (val){
} case 1:
testlogic(10); answer = “alpha”;
 No break;
case 2:
testlogic (50); answer = “beta”;
 Yes break;
case 3:
Else If statement answer = “gamma”;
-statements used to be added to further subdivide break;
else statements case 4:
answer = “delta”;
function testlogic(val){ break;
if (val >= 50) { default:
return “Yes”; answer = “None”;
} else if (val <40){ break;
Return “Between 40 to 50”
} else { }
Return “No”; return answer;
} }
testlogic(10);
 No [Link](caseSwitch(1);
testlogic(41);  alpha
7
[Link](caseSwitch(a); Boolean values after functions
 None
Example:

function isLess (a,b){


Break – breaks the statement and goes to the end return a < b;
of the statement immediately for exit }
[Link] (isLess(10,15));
Default option is like the else statement  true

Return early pattern from function

function caseSwitch(val){ function abTest(a,b) {


var answer = “”; if (a < 0 || b < 0) {
switch (val){ return undefined;
}
case 1:
case 2: return [Link]([Link]([Link](a)
case 3: + [Link](b), 2));
answer = “low”; }
break;
case 4: [Link] (abTest(-2,2));
case 5:  undefined
case 6:
answer = “mid”; Objects
break;
case 7: - similar to arrays, instead of using indexes,
case 8: uses properties
case 9:
answer = “high”; Example:
break;
} Var ourDog = {
return answer; “name”: “Camper”,
} “legs”: 4,
[Link] (caseSwitch(5)); “tails”: 1,
 mid “friends”: [“everything!”]
[Link] (caseSwitch(1)); };
 low

Access a property in an object

8
- to test the property of an object, you can };
use the DOT notation
[Link] = “Happy Camper”;
Example:
var myDog = {
Var testObj = { “name”:”Coder”,
“hat”:”ballcap”, “legs”:4,
“shirt”:”jersey”, “tails”:1,
“shoes”:”cleats; “friends”: [“freeCodeCamper”]
}; };

Var hatValue = [Link];


Var shirtValue = [Link]; [Link] = “Happy Coder”;

[Link] (hatValue); var dogname = [Link];


 “ballcap” [Link] (dogname);
 Happy Coder
The above figures can also be done using the
BRACKET notation
Adding new properties to objects
var hatValue = testObj[“hat”];
[Link] (hatValue); var myDog = {
 Ballcap “name” : “happy coder”,
“legs” : 4,
Object properties can also be collected using “tails” : 1,
VARIABLES “friends” : [“FCC”]
};
Example:
Var testObj = { myDog[‘bark’] = “woof”;
12: “Namath”,
16: “Montana”, var newItem = [Link];
19: “Unitas” [Link](newItem);
};  woof

var playerNumber = 16;


var player = testObj[playerNumber]; Deleting properties to objects
[Link] (player);
 “Montana” var myDog = {
“name” : “happy coder”,
Updating Object Properties “legs” : 4,
“tails” : 1,
var ourDog = { “friends” : [“FCC”]
};
“name”, “Camper”,
“legs”: 4, delete [Link];
“tails”: 1,
“friends”: [“everything!”] var deletedItem = [Link];
9
[Link](deletedItem); var lookup = {
 undefined “alpha”:”Chua”,
“bravo”: “Mikee”,
“lovey”: “Troyss,
};
result = lookup[val];
};
[Link] (phoeneticlookup(alpha));
 Chua

Using Objects for Lookup


Testing Objects for Properties
Alternative for a long switch function is a short use
of the Object JS programming var myObj = {
gift: “pony”,
Instead of this >>> pet: “kitten”
};
function phoeneticlookup (val) {
var result = “”; function checkObj(checkProp){
if ([Link](checkProp)){
switch (val) { return myObj[checkProp];
case “alpha”: } else {
result = “Chua”; return “not found”
break; }
case “bravo”: }
result = “Mikee”; [Link](checkObj(gift));
break;  “pony”
case “lovey”:
result = “Troyss”; Manipulating complex objects
break;
- Objects can store complex data
};
var myMusic = [
You can use this >>> {
“artist”:”Billy Joel”,
function phoeneticlookup (val) { “title”: “Piano Man”,
var result = “”; “release_year”: 1973,
“formats”: [
10
“CD”, var getList = [Link]["Immediate"]
“8T”, ["Parents"];
“LP” [Link](getList);
],  [“Marlon”, “Belen”]
“gold”: true
}, Iteration with WHILE loops
{
“artist”: “Beau”, var myArray = [];
“title”: “Cereal”, var i = 0;
“release_year”: 2021, while (i<5){
“formats”: [ [Link](i);
“YT video” i++;
] }
]; [Link](myArray);
 [0,1,2,3,4]

Accessing Nested Objects


Iterate with FOR loops
- To access complex nested objects
Syntax:
- Chain the BRACKET or DOT notations to get for (Declaration variable, run condition, function
the different levels for the variable) {
function for the expression
Example: }

var Mikee = { var ourArray = [];


"Details":{ for (var I = 0; i < 5; I++) {
"Recent":
{ [Link](i);
"Love":"Troyss", }
"Pet": "Basha"
}, [Link](ourArray);
"Immediate":  [0,1,2,3,4]
{
"Parents": Nesting for loops
["Marlon",
"Belen"], Example:
"Brother": "Mark"
}, function multiplyAll(arr) {
} var product = 1;
}
for (var i=0, i< [Link]; i++){
11
for (var j=0; j <arr[i].length; j++){
product *= arr[i][j] do {
} [Link](i);
} i++;
return product; } while (i<5)
[Link](i,myArray);
var product = multiplyAll([[1,2], [3,4],[5,6,7]]);  11[10]
}
[Link](product); Generate random Fractions
 5040
Example:
function randomFraction() {

return [Link]();
}
[Link] (randomFraction());
 0.27156

Syntax to set a number between specific numbers

[Link]() * SpecificNumber

Iterating using Do WHILE loops


var randomNumberBetween0and19 =
While loops – first checks the condition before it [Link]([Link]())*20);
runs any code within the loop function randomWholeNum(){

Do While loop – run at least one time THEN it return [Link]();


checks the condition }
[Link](randomWholeNum());
Example:
Generating whole numbers within a range
WHILE LOOP
var myArray = []; Example:
var i = 10; function ourRandomRange(ourMin, ourMax) {
return [Link]([Link]() *
while (i<5) { (ourMax- ourMin +1)) + ourMin;
[Link](i); }
i++;
} var randomRange = ourRandomRange (1,9);
[Link](i,myArray); [Link] (randomRange);
 10 []  8

DO WHILE LOOP
var myArray = []; Using the parseInt function
var i = 10;
12
- Takes a string and returns an integer return a===b ? true:false;
- If string cannot be returned to an integer it
returns an NaN.= Not a Number return a===b;

Example:
Using multiple conditional (Ternary) operators
function convertToInteger(str) {
return parseInt(str); function checkSign(num) {
} return num > 0 ? “positive” : num < 0 ?
convertToInteger (“56”); “negative” : “zero”;
}
[Link](10);
Using the parseInt function with a Radix

function convertToInteger(str){ Difference of var and let keywords


return parseInt(str, 2)
} Let – does not let you declare a variable twice
Var – allows you to declare a variable multiple
convertToInteger(“10011”); times

If you want to declare the variable twice using


“let”, use the syntax: variable = “value”

Put “use strict”; command to catch coding mistakes


in a program
Use the Conditional (Ternary) Operator
Compare scopes of the var and let keywords
- condition ? statement-if-true: statement-if-
false; Var – declared globally or locally when in a function
Let – scope is limited to the block statement or
Example: expression that it was declared in

function checkEqual(a, b) {
if (a === b) { Declaring a read-only variable with the const
return true; Keyword
}
else { - It is not possible to reassign a “const”
return false; variable
}
} const sentence = str + “is cool!”;
checkEqual(1,2);
[Link](checkEqual(1,2); sentence = “Troyss”

 SyntaxError: unknown “sentence” is read


FOR TERNARY OPERATOR INSTEAD only

function checkEqual(a,b){ Mutate an array with a declared const


13
- Change the array content even though it Const PI = freezeObj();
was declared as const using the bracket
notation Use Arrow Functions to write Concise Anonymous
Functions
Example:
- Anonymous function – it doesn’t have a
const s = [5,7,2]; name but is assigned to a variable
function editInPlace() { - Syntax to be converted to arrow function
“use strict”;
Example:
s [0] = 2; FROM THIS
} var magic = function() {
editInPlace(); return new Date ();
[Link](s); };
 [2,7,2]
TO THIS
const magic = () => new Date ();

Prevent Object Mutation


Write Arrow Functions with Parameters
- Use the syntax [Link] to make sure
that the variable won’t be changed at all - Just like a normal function, it is possible to
pass multiple arguments in a function
function freezeObj() {
“use strict”; Example:
const MATH_CONSTANTS = { FROM THIS
PI:3.14 var myConcat= function(arr1,arr2) {
}; return [Link](arr2);
};
[Link](MATH_CONSTANTS); [Link](myConcat([1,2],[3,4,5]));

try { TO THIS
MATH_CONSTANTS.PI = 99;
} catch( ex ) { const myConcat = (arr1,arr2) => [Link](arr2);
[Link](ex); [Link](myConcat([1,2],[3,4,5]));
}  [1,2,3,4,5]
return MATH_CONSTANTS.PI;
} Write higher order arrow functions
14
- Arrow functions work really well with higher
order functions such as map, filter, and - Rest Operator allows you to create a
reduce function that takes a variable number of
- Takes functions as arguments for processing arguments
collections of data - Rest operator notation – [ . . . ]
- In this example, instead of accepting only
Example: Filtering out only positive integers three variables, you can now accept even 4
or even more numbers of variables
const realNumberArray = [4,5.6, -9.8, 3.14, 42,
6,8.34, -2]; Example:
const sum = (function() {
const squareList=(arr) => { return function sum(x,y,z) {
const squaredIntegers = [Link](num=> const args = [x,y,z];
[Link](num) && num > 0).map(x => x*x); return [Link]((a,b) => a+b, 0);
/*.map gets the values through an };
assignment of variable x to continue for another })();
function*/ [Link](sum(1,2,3));
return squaredIntegers;  6
}; THIS CAN BE WRITTEN INSTEAD AS:

const squaredIntegers = const sum = (function() {


squareList(realNumberArray); return function sum(…args){
[Link](squaredIntegers); return [Link]((a,b)=> a + b, 0);
 16, 1764, 36 };
})();
[Link](sum(1,2,3));
 6
[Link](sum(1,2,3,4));
 10
More flexible arrow functions with default
parameters Use the Spread Operator to Evaluate Arrays In-
Place
Default parameter kicks in when there is no
argument specified in a function - Spread operator looks very the same as a
rest operator
Example: - Spread operator notation – [ . . .]
- Allows an array to be a literal copy of
const increment = (function () { another array
return function increment (number,value = 1) {
// value = 1 sets it as 1 by default Example:
return number + value;
}; const arr1 = [‘Jan’, ‘Feb’, ‘Mar’, ‘Apr’, ‘May’];
}) (); let arr2;
[Link](increment(5,2)); (function() {
[Link](increment(5)); arr2 = arr1;
arr1[0]=’potato’
Use of the Rest Operator with Function Parameters })();
15
[Link](arr2); return maxOfTomorrow;
 [potato, Jan, Feb, Mar, Apr, May] }
[Link](getMaxOfTmrw(LOCAL_FORECAST));
TO CHANGE THIS TOWARDS MAKING ARRAY 1 a  84.6
copy of ARRAY 2
Use Destructuring Assignment to Assign Variables
const arr1 = [‘Jan’, ‘Feb’, ‘Mar’, ‘Apr’, ‘May’]; from Arrays
let arr2;
(function() { Example:
arr2 = […arr1]; const [z,x, , y] = [1,2,3,4,5,6];
arr1[0]=’potato’ [Link](z,x,y);
})();  1,2,4
[Link](arr2); - 3 was skipped because of the ( , ,) double
 [Jan, Feb, Mar, Apr, May] comma that was put to skip an item in the
array

To rearrange items in an array:

Let a = 8, b = 6;
(()=> {
“use strict”;
[a,b] = [b,a]
})();
[Link](a);
[Link](b);
 6
 8

Destructuring Assignment with Nested Objects


Use Destructuring Assignment with the Rest
Syntax: Operator
{identifier: receiving variable} = variable name
- Use destructuring assignment with the rest
Example: operator to reassign array elements

const LOCAL_FORECAST = { const source = [1,2,3,4,5,6,7,8,9,10];


today: { min: 72, max:83 }, function removeFirstTwo(list) {
tomorrow: { min:73.3, max: 84.6 } const [, , …arr] = list;
}; return arr;
}
function getMaxOfTmrw(forecast){ const arr = removeFirstTwo(source);
“use strict”; [Link](arr);
const { tomorrow: {max: maxOfTomorrow }} =  [3,4,5,6,7,8,9,10]
forecast; [Link](source);
16
 [1,2,3,4,5,6,7,8,9,10] })();
[Link](stats);
Use Destructuring Assignment to Pass an Object as [Link](half(stats));
a Function’s Parameters  max: 56.78, stdev: 4.34, median: 34.54,
mode: 23.87, min: -0.75, average: 35.85
- Used for API calls that usually gives a lot of  28.015
information than what is needed
Example: Create strings using template literals
const stats = {
max: 56.78, - Template Literals
stdev: 4.34, o Special type of string that makes
median: 34.54, creating complex strings easier
mode: 23.87,
min: -0.75, Example:
average: 35.85
}; const person = {
const half = (function(){ name: “Zodiac Hasbro”;
return function half(stats){ age: 56
return ([Link]+[Link])/2.0; };
};
const greeting = `Hello, my name is $
})(); {[Link]}! I am ${[Link]} years old`;
[Link](stats); [Link](greeting);
[Link](half(stats));  Hello, my name is Zodiac Hasbro! I am 56
 max: 56.78, stdev: 4.34, median: 34.54, years old.
mode: 23.87, min: -0.75, average: 35.85
 28.015 $ - assign a dynamic variable in a string
` - backticks for template literals
INSTEAD OF THIS IT CAN BE REWRITTEN AS:

const stats = { Write Concise Object Literal Declarations Using


max: 56.78, Simple Fields
stdev: 4.34,
median: 34.54, Example:
mode: 23.87, const createPerson = (name, age, gender) => {
min: -0.75, Return {
average: 35.85 name: name,
}; age: age,
const half = (function(){ gender: gender
return function half({max, min}){ };
return (max + min)/2.0; };
}; [Link](createPerson(“Zodiac Hasbro”,
56,”male”));
17
 [name:”Zodiac Hasbro”, age: 56, gender: constructor(targetPlanet){
“male”] [Link]=targetPlanet;
YOU CAN WRITE THIS SIMPLER WITH: }
}
const createPerson = (name, age, gender) var zeus = new SpaceShuttle (‘Jupiter’);
=>{name, age, gender}; [Link]([Link])
[Link](createPerson(“Zodiac Hasbro”,  Jupiter
56,”male”));
 [name:”Zodiac Hasbro”, age: 56, gender: Use getters and setters to Control Access to an
“male”] Object

Write Concise Declarative Functions Class Object – you will want to obtain values from
Example: an object and set a value within an object called
const bicycle = { Getters and Setters
gear: 2,
setGear: function(newGear) { Getters = to return or get the value of an object’s
“use strict”; private variable to the user without the user
[Link] = newGear; directly accessing the variable
}
}; Setter = to overwrite a value
[Link](3);
[Link]([Link]); class Book {
 3 constructor(author) {
this._author = author;
THIS CAN BE WRITTEN SHORTER BY: }
const bicycle = { get writer (){
gear: 2, return this._author;
setGear: (newGear) { }
“use strict”;
[Link] = newGear; set writer (updatedAuthor){
} this._author = updatedAuthor;
};
[Link](3); this. – keyword that the variable is only accessible
[Link]([Link]); within the class
 3 _ - use of underscores meant to signify that the
Use class Syntax to Define a Constructor Function variable are only accessible in the class
Understand the Differences between import and
var SpaceShuttle = function(targetPlanet){ require
[Link] = targetPlanet;
} Import/Export – to use a certain data from a file to
var zeus = new SpaceShuttle(“Jupiter”); be used on another file
[Link]([Link])
Example:
YOU CAN WRITE THIS INSTEAD USING “CLASS” and
“CONSTRUCTOR” [Link]
const cap = capitalizeString(“hello!”);
class SpaceShuttle { [Link](cap);
18
You can do:
String_function.js export default function subtract (x,y) {return x -y};
export const capitalizeString = str =>
[Link]() Import a default export

TO USE THE STRING_FUNCTION.JS TO [Link] Example:

Import { capitalizeString } from “./string_function” Under Math_functions.js


const cap = capitalizestring(“hello!”); subtract (7,4);
[Link](cap);
 HELLO! to import a default export:

Syntax: import subtract from “math_functions”;

Import { FUNCTION NAME } from “./filename”

Use export to reuse a code block

- Use export functions and variables from one


file so that you can import them into
another file

Add “export” to the start of each line of code you


want to export

Use * to import everything from a file

- Importing everything requires the creation


of an object and direction where to get

Example:
Import * as capitalizeStrings from
“capitalize_strings”

Syntax:
Import * as (name of Object) from “./filename”;

Creating an export fallback with export default

Export default – a fall back export when you only


want to export one thing from a file

Example:

If you want to export


function subtract(x,y) { return x-y;}

19

You might also like