首页 > 其他分享 >Values, Types, Operators and Type Coercion

Values, Types, Operators and Type Coercion

时间:2023-01-24 05:00:11浏览次数:85  
标签:false Type Operators NaN value values typeof Coercion operators

All Types All the Time

In this set of slides, we'll take a look at:

  1. JavaScript's types
  2. Numbers and numeric operators
  3. Strings and string operators
  4. Booleans and logical and comparison operators
  5. undefined and null

Some Definitions

  • value - data
  • type - a category or classification of values
  • operator - a language construct that allows the manipulation or combination of a value or values to yield another value
  • operand - a value that an operator works on; the subject of an operator
  • unary operator - an operator that only has one operand
  • binary operator - an operator that has two operands
  • prefix operator - an operator that goes before (to the left) of its operand(s)
  • infix operator - an operator that goes between its operands

typeof

Before we delve into these data types, let's check out a unaryprefix operator:

typeof

As you might expect, typeof returns a string that represents the operand's type:

> typeof 317.0
'number'

We'll be using typeof extensively for the next few slides….

TELL ME ABOUT THE TYPES!

Seriously, stop messing around. Types Really:


Functions are actually just objects, but typeof gives back function when its operand is a function. Arrays are objects too, so typeof returns object for an Array.

Primitives vs Objects

Hey… those two terms should sound familiar… →

  • booleans, numbers, strings, null and undefined are primitive values:
    • they're immutable
    • they're compared by value
    • note that wrapper objects for primitives do exist (we'll see this later)
  • objects, on the other hand:
    • are compared by reference
    console.log({} === {}) // false!
    const foo = {};
    const bar = foo;
    console.log(foo === bar); // true (because "aliasing")
    • are mutable (by default, though they can be made immutable-ish) 

More About Numbers

  • So how many values can 64 bits hold? (Um… a lot?) →
  • 2 to the power of 64! About 18 with 18 0's after it. However, this doesn't exactly indicate what numbers can be stored. Why? →
  • This just means that number of possible values. This has to include negative numbers, decimals, etc…
    • 52 bits for the value (er really 53 … because of the sign)
    • used to represent both integers and real numbers
    • 11 bits for the exponent (for placing the decimal point)
    • 1 bit for the sign

Some Special Numbers…

Try the following operations… →

0/0
9e300 * 25874481
  • JavaScript has some special number values:
    • NaN (Not a Number) - this results from any numeric operation that doesn't give back a meaningful result…
    • Infinity, -Infintity - positive and negative infinities
  • Note that these special values are actually numbers! (really!)
    • that is, both NaN and Positive/Negative Infinity are of type Number! →
      typeof NaN      // --> number (what??? ok)
      typeof Infinity // --> number
 

More About NaN

Again, NaN stands for not a number

  • NaN is toxic …
  • using it in any other numeric operations always results in NaN →
    • NaN + 1 → NaN
  • the only way to check if a value is NaN is by using the built-in function isNaN(val)
  • oddly, NaN === NaN is false (!? … as specified by IEEE)
 

More About Infinity

So, there's  Infinity and  -Infinity

  • Infinity + 1 or Infinity + Infinity→ is still Infinity
  • Infinity represents all values greater than 1.79769313486231570e+308
  • dividing by 0 yields infinity
  • equality operators and the global function isFinite can be used to determine if a value is Infinity

Strings Continued

string can be composed of any characters: numbers, letters, punctuation, spaces, etc.

The following is a string with nothing in it… or an empty string: ""

String Operators

A few string operators:

  • string concatenation, or +, is an operator that takes two strings and joins them:
    "hello " + "there"
  • indexing, or []… can be used to retrieve the character at an index, such as 'emoji'[3] (or use charAt)
  • comparison operators, you can use <<=, etc. … unicode code points are compared 'B' > 'A' // true

Booleans

boolean is a data type that has two possible values: true or false.

As one would expect, the literals for these values are (all lowercase):

true
false
 

Inherent Truthiness

When non-boolean types are converted to booleans, the followings rules are used →

  • 0NaN, empty string (""), and undefined/null are false
  • other values are true-ish

 

Let's test this out… →

// outputs "in here"
if("this string says false, but...!?") {
	console.log("in here!");
}

// no output
var myString = "";

if(myString) {
	console.log("you shouldn't see me!");
}
 

Logical Operators

Boolean values can be combined and manipulated using logical operators.  What are some logical operators, and what do they do? →

  • and - && - returns true if and only if both operands are true, otherwise, returns false
  • or - || - returns false if and only if both operands are false, otherwise, returns true
  • not - ! - returns the opposite boolean value of its single operand to the right

And and Or With Non Boolean Values

Some details about && and ||:

  • if operands are not actually boolean, convert the value on the left side to a boolean
    • ||
      • will return the left operand's value if it's true
      • otherwise, return the value on the right
      • can be used as a way to fall back to a default value potentially_falsey || default_value
    • &&
      • will return the left operand's value if it's false
      • otherwise, return the value on the right
  • also… short-circuit evaluation applies
 

And and Or Continued

Based on the previous slide, what are the values produced by the following expressions? →

5 - 5 || 2
5 - 5 && 2
"hello" || "goodbye"
"hello" &&  "goodbye"
2
0
hello
goodbye

This syntax is actually sometimes used to assign a default value if a value doesn't exist:

// we haven't seen objects yet, but you get the idea
const obj = {prop1: "a value"}; 
const val1 = obj.prop1 || "default value"
const val2 = obj.prop2 || "default value"

Ternary Operator

What will this code return?

true ? "ok" : "not ok!"
  • "ok"
  • format is test (boolean expression) ? value to return if true : value to return if false


The ternary operator works like an if/else statement, but it's one line and it evaluates to a value:

// ternary followed by equivalent if/else
let x = 5 > 2 ? 'yes' : 'no';

let x;
if(5 > 2) {
    x = 'yes';
} else {
    x = 'no';
}
 

Comparison Operators

Booleans can be produced from comparison operators. Without knowing anything about JavaScript, what do you think are some available comparison operators? →

  • <><=>= - greater than, less than, etc.
  • === - equals, checks both type and value
  • !== - not equals, checks both type and value
  • == - equals, coerces operands to appropriate types
  • != - not equals, coerces operands
 

Comparison Operators Continued

Comparison Operators are binary , infix operators that can be used to compare two operands:

  • numbers are obvious: 5 > 2 →
  • strings are compared from left to right (by character code): "aardvark" > "bison" (more or less, alphabetic) →
  • NaN is the only value not equal to itself →
  • You'll probably always want to use === →
 

undefined and null

See the section on undefined and null in our book

  • undefined means no value
    • think of a function that doesn't return a value
    • or the value of a declared variable that hasn't been given a value yet
    • or a missing argument to a function
  • null means "no object"… it's a value that can be assigned to a variable to represent "no object" →
  • the subtle differences between undefined and null are an accident of language design!
    • you'll typically find undefined when something wasn't initialized
    • you'll find null if an object is explicitly set to null
 

Type Coercion

What values would you expect from the following lines of code? →

5 + 5
"5" + 5
"five" + 5
5 == "5"
5 === "5"
5 * undefined
5 * null
10
'55'
'five5'
true
false
NaN
0

 

How do we know? We can read the ECMAScript specifications!

Type Coercion With Numeric Operators

  • for addition:
    • when one operand is a string and the other is not, the other operand is converted into a string, and the two strings are concatenated
    • for all other cases, the operands are converted to numbers
      • true → 1
      • false → 0
      • null → 0
      • undefined is still undefined, and result gives back NaN
  • for other numeric operators, such as subtraction:
    • will usually try to convert to number
    • if something cannot be converted easily (like the string, "hello"), the result is NaN
 

Type Coercion With Equality Operators

  • JavaScript will do its best to convert types so that they can be checked for equality - these all return true →
    • "10" == 10
    • 0 == false
    • "" == false
  • this is Usually an unwanted behavior; to avoid this, use: === and !==
    • these operators check type and value
    • use these three-character comparison operators to prevent unexpected type conversions


If you want to see the details for every possible operand combination for double equalscheck out mdn's table

标签:false,Type,Operators,NaN,value,values,typeof,Coercion,operators
From: https://www.cnblogs.com/M1stF0rest/p/17065764.html

相关文章

  • 关于typescript异构枚举实现解析
    这里有几种实现方式:第一种是:A,B的实现Enum[Enum["A"]=0]="A";x=Enum["A"]=0;//x的值为0也就是说:Enum有两个键值:一个是0,他的值是“A”;一个是“A”,他的值是0;Enum......
  • Blob文件下载type类型
    leturl=window.URL.createObjectURL(newBlob([文件流(一般为res.data)],{type:"Blob类型"})letlink=document.createElement('a')link.style.dispaly='none'l......
  • typescript联合类型的类型缩减使用
    never是所有类型的子类型当我们想要一个这样一个类型时困难1因为采用索引签名要满足所有成员都必须符合字符串的索引签名所有不能采用{[index:string]:string|ag......
  • typesafe config 简单试用
    以前我简单介绍过dremio关于typesafeconfig的使用说明,还是比较强大的,以下是一个简单的学习使用项目配置参考图  内容application.conf会引用defaultvalues.......
  • Doris报Could not initialize class org.apache.doris.catalog.PrimitiveType
    ERROR1105(HY000):errCode=2,detailMessage=NoClassDefFoundError:Couldnotinitializeclassorg.apache.doris.catalog.PrimitiveType这个报错是jar包的问题1.......
  • Array.prototype.at
    概念Array.prototype.at方法根据索引位置,返回数组中对应的元素。语法arr.at(index)参数index需要检索的位置。返回值返回数组中索引的元素。如果索引不在数组......
  • Array.prototype.concat
    概念Array.prototype.concat方法将数组实例中的元素与添加一个或多个元素(数组)合并成一个新数组。语法arr.concat(element1)arr.concat(element1,element2)arr.conca......
  • [Typescript 4.9] TypeScript 4.9: satisfies operator
    Previously,wehaveproblemforsuchcode:typeRGB=readonly[red:number,green:number,blue:number];typeColor={value:RGB|string};constmyColor......
  • 写JS的过程中摁F12发现:Uncaught TypeError: Cannot set properties of null (setting
    在写JavaScript的过程中出现如上图显示的问题,很有可能是onblur前面的类型和你定义的类名不一样,要仔细检查一下你写的类名前后是否一致。......
  • 【TypeScript】学习笔记
    一.环境搭建安装Node.jsnpmi-gtypescript创建ts文件test.ts,编译:tsctest.ts二.基本类型1.类型声明语法:let变量:类型;let变量:类型=值;functionfn(参数:类型,参数:......