Unary Operators
Unary operators require only one operand to perform an operation.
The delete Operator
The delete
operator is used to delete an object's property or an element at a specified index in the array.
NOTE
When using the delete
operator on an array, the array is NOT reindexed and the length is not changed. Therefore, using the delete
operator with arrays is generally discouraged. Use the splice()
method instead.
const person = {
name: 'Ted',
age: 21
}
console.log(person) // {name: 'Ted', age: 21}
delete person.age
console.log(person) // {name: 'Ted'}
const colors = ['red', 'green', 'blue']
console.log(colors) // ['red', 'green', 'blue']
delete colors[1]
console.log(colors) // ['red', undefined, 'blue']
The typeof Operator
The typeof
operator returns a string indicating the type of the following operand.
const name = 'Ed'
const pi = 3.14
const enrolled = true
console.log(typeof 'Ted') // string
console.log(typeof name) // string
console.log(typeof 21) // number
console.log(typeof pi) // number
console.log(typeof ['red', 'green']) // object
console.log(typeof {name: 'Ted'}) // object
console.log(typeof true) // boolean
console.log(typeof enrolled) // boolean
console.log(typeof undeclaredVariable) // undefined
Before the introduction of ES2015, typeof
was a guaranteed safe way to return a the datatype of a variable, even with undeclared variables. But with introduction let
and const
, which use block-scope, a ReferenceError
can occur if the variable is declared after the typeof
operator is used on the same variable.
console.log(typeof undeclaredVariable) // undefined
console.log(typeof name) // ReferenceError
const name = 'Ted'