Operators

Estimated reading: 2 minutes 151 views

Basic Operators

Basic operators allow you to manipulate values.

Concatenation

				
					var foo = "hello";
var bar = "world ";
console . log ( foo + " " + bar ); // "hello world "
				
			

Arithmetic Operators

				
					let a = 10;
let b = 5;

console.log(a + b); // Output: 15
console.log(a - b); // Output: 5
console.log(a * b); // Output: 50
console.log(a / b); // Output: 2
console.log(a % b); // Output: 0

				
			

Incrementing and decrementing

				
					var i = 1;
var j = ++i; // pre - increment : j equals 2; i equals 2
var k = i ++; // post - increment : k equals 2; i equals 3

				
			

Operations on Numbers & Strings

In JavaScript, numbers and strings will occasionally behave in ways you might not expect.

Addition vs. concatenation

				
					var foo = 1;
var bar = ’2 ’;
console . log ( foo + bar ); // 12. uh oh
				
			

Forcing a string to act as a number

				
					var foo = 1;
var bar = ’2 ’;
// coerce the string to a number
console . log ( foo + Number ( bar ));
				
			

Logical Operators

Logical operators allow you to evaluate a series of operands using AND and OR operations.

Logical AND and OR operators
				
					var foo = 1;
var bar = 0;
var baz = 2;
foo || bar ; // returns 1 , which is true
bar || foo ; // returns 1 , which is true
foo && bar ; // returns 0 , which is false
foo && baz ; // returns 2 , which is true
baz && foo ; // returns 1 , which is true
				
			

Comparison Operators

Comparison operators allow you to test whether values are equivalent or whether values are identical.

Comparison operators
				
					var foo = 1;
var bar = 0;
var baz = ’1 ’;
var bim = 2;
foo == bar ; // returns false
foo != bar ; // returns true
foo == baz ; // returns true ; careful !
foo === baz ; // returns false
foo !== baz ; // returns true
foo === parseInt ( baz ); // returns true
foo > bim ; // returns false
bim > baz ; // returns true
foo <= baz ; // returns true

				
			
Share this Doc

Operators

Or copy link