DEV Community

Dahye Ji
Dahye Ji

Posted on • Updated on

JavaScript Basic - Variable, Data Types, Operators, Comparisons

I'm gonna practice on developer's tool, you can open it by pressing cmd+opt+i or F12 on mac / ctrl+shift+i on window.

developer's tool
(type about:blank in browser's address bar if you want empty page and go to Console.)

Inline

When a script tag is used in the HTML file, it is called inlining. This means no external JS file is used instead javascript is put into an HTML file/

Script

Having external JS file and you can add it with <script></script> tag in the HTML file.

Variables

Variables are containers for storing data values. Variables are named containers that you can place data in and then refer to the data by naming the container.
JavaScript has three ways of declaring variable.

// = is assignment operator
// var myDog; // undefined
var myDog = 'jamong';
// var is key word
// myDog is variable name
// 'jamong' is value
Enter fullscreen mode Exit fullscreen mode

Naming variables

Invalid variable

var 1stAnimal = 'Snake'; // starts with number
var var = 'variable'; // keyword/reserved word (var is keyword)
var fist name = 'John' // space(whitespace)
Enter fullscreen mode Exit fullscreen mode
  • Variable name in JavaScript cannot include full stop(.), comma(,), whitespace annd special characters excluding $ and underscore(_).
  • The first letter of variable cannot be a number.
  • JavaScript is case sensitive.
  • Reserved Words in JavaScript cannot be used as variable names.
  • You can use unicode.

Valid variable

// starts with lower/upper case letter
var fruit = 'mango'; 
var my_name = 'Hailey'; 
var my123 = '123';

// starts with $
var $money = '7'; 

// begins with underscore
var _weather = 'sunny'; 
Enter fullscreen mode Exit fullscreen mode

camelCase (more readable if it's more than one word)

//camelCase
favouritecolour = 'black'; // bad practice
FAVOURITECOLOUR = 'black'; // bad practice
favouriteColour = 'black'; // best practice. this is more readable than others.
Enter fullscreen mode Exit fullscreen mode
var myName = 'Hailey';
myName = 'Chloe';
// with var and let, you can reassign variable
Enter fullscreen mode Exit fullscreen mode

var, let, const

There are three ways to declare variables.

var

:var is function scoped.

let

: let is an alternative to var. let is block scoped.

const

: const is block scoped. can't change const value through reassignment.

** BUT! I'm going to write about the scope later and will only use let util then.

Data Types

  • String (eg. "hello", " " is also string which has whitespace) : A string may have zero or more characters, there’s no separate single-character type.
  • Numbers (eg. 1, 2.5 ..) : for numbers of any kind, integer or floating-point, integers are limited by ±(253-1).
  • BigInt :It's rarely used. It's to cover large number because in JavaScript, the “number” type cannot represent integer values larger than (253-1) (that’s 9007199254740991), or less than -(253-1) for negatives. It’s a technical limitation caused by their internal representation.)
  • Boolean (true / false)
  • null : null value does not belong to any of the types described above. It’s a special value which represents “nothing”, “empty” or “value unknown”.)
let age = null;
// The code above states that age is unknown.
Enter fullscreen mode Exit fullscreen mode
  • Undefined : The meaning of undefined is “value is not assigned”
let age;
alert(age); // shows "undefined"
Enter fullscreen mode Exit fullscreen mode
  • Object
  • Symbols

typeof / typeof()

// You can check type of data using typeof
// typeof x (as an operator)
// typeof(x) (as a function) 
typeof(123);
typeof("Hailey")
typeof(true)
Enter fullscreen mode Exit fullscreen mode

String

let name = 'Hailey';
let name = "Hailey"; 
// You can use ''(single quote) or ""(double quote).
// Choose one implementation, either single or double quote, and use consistently.
// Teams will often have agreed upon style guide.

// Change to string
String(123) // '123'
let x = 10
x.toString() // '10'
123 + '' // '123'
Enter fullscreen mode Exit fullscreen mode

Data type - String

type of 24 // number
type of '24' // string
type of true; // boolean
type of 'true' // string
Enter fullscreen mode Exit fullscreen mode

Single or Double Quotes Within Strings

let greeting = 'It's great to see you' // error
// You can use this way
let greeting = 'It\'s great to see you' 
let greeting = "It's great to see you"

let response = "Chloe said, "I'm busy now"" // error
// You can use this way
let response = "Chloe said, \"I'm busy now\"" // error
let response = 'Chloe said, "I'm busy now"'

Enter fullscreen mode Exit fullscreen mode

Template literals / String Concatenation

let name = 'Jamong';
let dogType = 'poodle';
let age = 5;
console.log(name + ' is ' + dogType + ' and she is ' + age +' years old');
//Template literals
console.log(`${name} is ${dogType} and she is ${age} years old`);
Enter fullscreen mode Exit fullscreen mode

Operators

  • Addition +
  • Subtraction -
  • Multiplication *
  • Division /
  • Remainder %
  • Exponentiation **
let num = 10%3
console.log(num)
// 1 (remainder of 10/3 which is 1)

console.log(2**2) // 2*2 = 4
console.log(2**3) // 2*2*2 = 8
console.log(2**4) // 2*2*2*2 = 16
Enter fullscreen mode Exit fullscreen mode

String concatenation with +

console.log('1' + 2); // "12"
console.log(2 + '1'); // "21"
console.log(2 + 2 + '1' ); // "41" and not "221"
console.log('1' + 2 + 2); // "122" and not "14"
Enter fullscreen mode Exit fullscreen mode

Numeric conversion, +

// No effect on numbers
let x = 1;
console.log(+x); // 1

let y = -2;
console.log(+y); // -2

// Converts non-numbers
console.log(+true); // 1
console.log(+""); // 0
console.log(+"5"); // 5
// It actually does the same thing as Number(...), but is shorter.

let apples = "2";
let oranges = "3";

console.log(apples + oranges); // "23", the binary plus concatenates strings
// both values converted to numbers before the binary plus
alert(+apples + +oranges); // 5
// same with (Number(apples) + Number(oranges));
Enter fullscreen mode Exit fullscreen mode

Modify-in-place

let n = 2;
n = n + 5;
n = n * 2;

let n = 2;
n += 5; // now n = 7 (same as n = n + 5)
n *= 2; // now n = 14 (same as n = n * 2)


Enter fullscreen mode Exit fullscreen mode

Increment/decrement

Increment ++ increases a variable by 1:

let counter = 2;
++counter; // works the same as counter = counter + 1, but is shorter
console.log(counter); // 3
Enter fullscreen mode Exit fullscreen mode

Decrement -- decreases a variable by 1:

let counter = 2;
--counter; // works the same as counter = counter - 1, but is shorter
console.log(counter); // 1
Enter fullscreen mode Exit fullscreen mode

The operators ++ and -- can be placed either before or after a variable.

  • When the operator goes after the variable, it is in “postfix form”: counter++.
  • The “prefix form” is when the operator goes before the variable: ++counter. ++counter; and counter++; are the same.

Comparisons

  • Greater than / less than: a > b, a < b
  • Greater than or equals / less than or equals: a >= b, a <= b
  • Equals: a == b

*Note: Double equality sign == means the equality test, while a single one a = b means an assignment.

  • Not equals: In maths the notation is ≠, but in JavaScript it’s written as a != b.
Boolean(2 > 1);  // true (correct)
Boolean(2 == 1); // false (wrong)
Boolean(2 != 1); // true (correct)

let result = 5 > 4; // assign the result of the comparison
console.log(result); // true
Enter fullscreen mode Exit fullscreen mode

Strict equality

Boolean(1 == "1"); // true
Boolean(1 === "1"); // false

Boolean(0 == false); // true
Boolean(0 === false); // false

// Boolean('') // false
// Boolean(' ') // true (string has whitespace, so it's true)
Boolean('' == false); // true
Boolean('' === false); // false
Enter fullscreen mode Exit fullscreen mode

There is also a “strict non-equality” operator !== analogous to !=

Comparison with null and undefined

For a strict equality check ===
These values are different, because each of them is a different type.

Boolean(null === undefined); // false
Enter fullscreen mode Exit fullscreen mode

For a non-strict check ==
There’s a special rule. These two are a “sweet couple”: they equal each other (in the sense of ==), but not any other value.

Boolean(null == undefined); // true
Enter fullscreen mode Exit fullscreen mode

Find more about null and undefined

For boolean values, true becomes 1 and false becomes 0

!!true // true
!!"Hello" // true
!!"" // false
!!1 // true
!!0 // false
!!undefined // false
!!NaN // false

!true // false
!(!true) // true
"0" == 0 // true
0 == "0" // true
false == "false" // false. because false is boolean, and "false" is string so it's true. false == true is false.
false == "0" // true. because == doesn't check if "0" is string it just consider it as 0 and 0 is false. false == false is true.
false === "0" // false. === check its data type as well. "0" is string and it's true. false===true is false.
false === 0 // true. 0 is false so false===false is true. 
false == null // false
false == undefined // false
false == NaN // false
f!!nul // false
!!undefined // false
!!NaN // false
Enter fullscreen mode Exit fullscreen mode

To read - Difference between Number and parseInt()

Logical operators

  • && (and): true only both are true
  • || (or): true if one of them are true
  • ! (not): the opposite (if !(true), false, if !(false), true)
false || true 
// true 
true && false
// false
!true
//false 
!( (true && false) || (true && false) )
// !(false||false) => !(false)
// true
let x =10
!((x%5 == 0 && x%2 == 0) || (x/2 == 5 && false))
// true || (true && false) => true || false
//false
let y = 10
(false && y % 2 ==0) && (x/2 == 5 && false)
// true && (true && false) => true && false
// false
Enter fullscreen mode Exit fullscreen mode

Top comments (0)