31 Matching Annotations
  1. Mar 2020
    1. Here is a more realistic example of the switch statement; it converts a value to a string in a way that depends on the type of the value: function convert(x) { switch(typeof x) { case "number": // Convert the number to a hexadecimal integer return x.toString(16); case "string": // Return the string enclosed in quotes return '"' + x + '"'; default: // Convert any other type in the usual way return String(x); } }

      Example

    2. One way to do this is with an else if statement. else if is not really a JavaScript statement, but simply a frequently used programming idiom that results when repeated if/else statements are used: if (n === 1) { // Execute code block #1 } else if (n === 2) { // Execute code block #2 } else if (n === 3) { // Execute code block #3 } else { // If all else fails, execute block #4 }

      Else If Statement

    3. Conditionals are statements like if and switch that make the JavaScript interpreter execute or skip other statements depending on the value of an expression. Loops are statements like while and for that execute other statements repetitively. Jumps are statements like break , return , and throw that cause the interpreter to jump to another part of the program

      Control Structure

  2. Feb 2020
    1. The left-hand expression is always evaluated, but its value is discarded, which means that it only makes sense to use the comma operator when the left-hand expression has side effects. The only situation in which the comma operator is commonly used is with a for loop ( §4.4.3 ) that has multiple loop variables: // The first comma below is part of the syntax of the let statement // The second comma is the comma operator: it lets us squeeze 2 // expressions (i++ and j--) into a statement (the for loop) that expects 1. for(let i=0,j=10; i < j; i++,j--) { console.log(i+j); }

      The Comma Operator

    2. The << operator moves all bits in its first operand to the left by the number of places specified in the second operand, which should be an integer between 0 and 31. For example, in the operation a << 1 , the first bit (the ones bit) of a becomes the second bit (the twos bit), the second bit of a becomes the third, etc. A zero is used for the new first bit, and the value of the 32nd bit is lost.

      Shift left with sign <<

    3. The >> operator moves all bits in its first operand to the right by the number of places specified in the second operand (an integer between 0 and 31). Bits that are shifted off the right are lost. The bits filled in on the left depend on the sign bit of the original operand, in order to preserve the sign of the result. If the first operand is positive, the result has zeros placed in the high bits; if the first operand is negative, the result has ones placed in the high bits.

      Shift right with sign >>

    4. The string passed to Symbol.for() appears in the output of toString() for the returned Symbol, and it can also be retrieved by calling Symbol.keyFor() on the returned Symbol. let s = Symbol.for("shared"); let t = Symbol.for("shared"); s === t // => true s.toString() // => "Symbol(shared)" Symbol.keyFor(t) // => "shared"

      String Passed

    5. JavaScript pre-defines global constants Infinity and NaN to hold the positive infinity and not-a-number value, and these values are also available as properties of the Number object: Infinity // A positive number too big to represent Number.POSITIVE_INFINITY // Same value 1/0 // => Infinity Number.MAX_VALUE * 2 // => Infinity; overflow! -Infinity // A negative number too big to represent Number.NEGATIVE_INFINITY // The same value -1/0 // => -Infinity -Number.MAX_VALUE * 2 // => -Infinity NaN // The not-a-number value Number.NaN // The same value, written another way 0/0 // => NaN Number.MIN_VALUE/2 // => 0: underflow! -Number.MIN_VALUE/2 // => -0: negative zero -1/Infinity // -> -0: also negative 0 -0 // The following Number properties are defined in ECMAScript 6 Number.parseInt() // Same as the global parseInt() function Number.parseFloat() // Same as the global parseFloat() function Number.isNaN(x) // Is x the NaN value? Works like x !== x Number.isFinite(x) // Is x a number and finite? Number.isInteger(x) // Is x an integer? Number.isSafeInteger(x) // Is x an integer -(2**53) < x < 2**53? Number.MIN_SAFE_INTEGER // => -(2**53 - 1) Number.MAX_SAFE_INTEGER // => 2**53 - 1 Number.EPSILON // => 2**-52: smallest difference between numbers

      Pre Defined

    6. Floating-point literals may also be represented using exponential notation: a real number followed by the letter e (or E), followed by an optional plus or minus sign, followed by an integer exponent. This notation represents the real number multiplied by 10 to the power of the exponent. More succinctly, the syntax is: [digits][.digits][(E|e)[(+|-)]digits]

      Floating

    7. In ECMAScript 6 and later you can also express integers in binary (base 2) or octal (base 8) using the prefixes 0b and 0o (or 0B and 0O ) instead of 0x : 0b10101 // => 21: (1*16 + 0*8 + 1*4 + 0*2 + 1*1) 0o377 // => 255: (3*64 + 7*8 + 7*1

      Integer Literals

    8. The string “é”, for example, can be encoded as the single Unicode character \u00E9 or as a regular ASCII e followed by the acute accent combining mark \u0301 . These two encodings typically look exactly the same when displayed by a text editor, but they have different binary encodings which means that they are considered different by JavaScript, which can lead to very confusing programs: const café = 1; // This constant is named "caf\u{e9}" const café = 2; // This constant is different: "cafe\u{301}" café // => 1: this constant has one value café // => 2: this indistinguishable constant has a different value

      Normalization

    9. The Unicode escape for the character é, for example, is \u00E9 , and here are three different ways to write a variable name that includes this character: let café = 1; // Define a variable using a Unicode character caf\u00e9 // => 1; access the variable using an escape sequence caf\u{E9} // => 1; another form of the same escape sequence Early versions of JavaScript only supported the four digit escape sequence. The version with curly braces was introduced to better support Unicode codepoints that require more than 16 bits such as emoji: console.log("\u{1F600}"); // Prints a smiley face emoji

      Unicode Escape Sequences

    10. The simplest course is to avoid using any of these words as identifiers, except, perhaps for from , set , and target which are safe to use and are already in common use. as const export get null target void async continue extends if of this while await debugger false import return throw with break default finally in set true yield case delete for instanceof static try catch do from let super typeof class else function new switch var

      Reserved Words

    11. The lexical structure of a programming language is the set of elementary rules that specifies how you write programs in that language. It is the lowest-level syntax of a language; it specifies such things as what variable names look like, the delimiter characters for comments, and how one program statement is separated from the next

      Lexical structure

  3. Dec 2019
    1. Consider this example:<?php$arr = ['name' => 'Bob', 'age' => 23 ];xdebug_debug_zval( 'arr' );The output from this script looks like this:arr: (refcount=1, is_ref=0)=array ('name' => (refcount=1, is_ref=0)='Bob','age' => (refcount=1, is_ref=0)=23)1

      Arrays and Objects

    2. Here is an example to illustrate:<?php$a = "new string";$b =& $a;// the variable b points to the variable axdebug_debug_zval( 'a' );xdebug_debug_zval( 'b' );// change the string and see that the refcount is reset$b = 'changed string';xdebug_debug_zval( 'a' );xdebug_debug_zval( 'b' );The output of this script is as follows:a: (refcount=2, is_ref=0)='new string'b: (refcount=2, is_ref=0)='new string'a: (refcount=1, is_ref=0)='new string'b: (refcount=1, is_ref=0)='changed string'We can see that until we change the value of $b it is referring to the same zvalcontainer as $a

      Copy on write example

    3. PieceDescriptionValueThe value the variable is set to.TypeThe data type of the variable.Is_refA Boolean value indicating whether this variable is part of a reference set. Remember that variables can be assigned by reference. This Boolean value helps PHP decide if a particular variable is a normal variable or if it is a reference to another variable.RefcountThis is a counter that tracks how many variable names point to this particular zval container. This refcount is incremented when we declare a new variable to reference this one.Variable names are referred to as symbols and are stored in a symbol table that is unique to the scope in which the variables occur.

      Memory management ways.

    4. as in this example:<?phpnamespace A { // this is in namespace A}namespace B { // this is in namespace B}namespace { // this is in the global namespace}

      Example

    5. Classes encapsulate code into instantiable units. Namespaces group functions, classes, and constants into spaces where their name is unique.The namespace declaration must occur straight after the opening <?php tag and no other statements may precede it.Namespaces affect constants, but you must declare them with the const keyword and not with define()

      Rule of using Namespaces

    6. To iterate over an array, you can use foreach, as follows:<?php$arr = [ 'a' => 'one', 'b' => 'two', 'c' => 'three'];foreach ($arr as $value) { echo $value; // one, two, three}foreach ($arr as $key => $value) { echo $key; // a, b, c echo $value; // one, two, three}

      iterate over an array eg;

    7. PHP’s most basic loop is the while loop. It has two forms, as shown:<?phpwhile (expression) { // statements to execute}do { // statements to execute} while (expression)

      While loop

    8. Conditional StructuresPHP supports if, else, elseif, switch, and ternary conditional structures.If structures look like this:<?phpif (condition) { // statements to execute} elseif (second condition) { // statements to execute} else { // statements to execute}Note that the space between else and if in the elseif is optional.If statements may be nested.The switch statement looks like this:<?phpswitch ($value) { case '10' : // statements to execute break; case '20' : // statements to execute break; case '30' : // statements to execute break; default: // statements to execute break;}Once a case matches the value, the statements in the code block will be executed until it reaches a break command.

      Conditional Structures

    9. It’s bad practice to suppress PHP errors with the @ operator. It is better to use PHP settings to suppress errors in your production environment and to allow your development environment to display errors. Having code that fails silently without producing an error makes debugging much more difficult than it needs to be.The last operator we will discuss is the backtick operator. It is not commonly used and is equivalent to calling the shell_exec() command. In the following example, the variable $a will contain the name of the user running the PHP interpreter.<?php// This is the equivalent of echo shell_exec('whoami');echo `whoami`;

      Suppressing

    10. Comparison OperatorsPHP uses the following comparison operators:OperatorDescription>Greater than>=Greater than or equal to<Less than<=Less than or equal to<>Not equal==Equivalence; values are equivalent if cast to the same variable type===Identity; values must be of the same data type and have the same value!=Not equivalent!==Not identical

      Comparison Operators

    11. By default, PHP assigns all scalar variables by value.PHP has optimizations to make assignment by value faster than assigning by reference (see the section on “Memory Management”), but if you want to assign by reference, you can use the & operator as follows:<?php$a = 1;$b = &$a; // assign by reference$b += 5;echo $a; // 6PHP always assigns objects by reference; if you try to explicitly create it by reference, PHP will generate a parse error.<?phpclass MyClass {}// Parse error: syntax error, unexpected 'new'$a = &new MyClass;

      Refrence Operator*

    12. PHP also has operators to shift bits left and right. The effect of these operators is to shift the bit pattern of the value either left or right while inserting bits set to 0 in the newly created empty spaces.To understand how these operators work, picture your number represented in binary form and then all the 1s and 0s being stepped to the left or right.The following table shows shifting bits, one to the right and one to the left.OperationOperationResult in BinaryResult in Decimal500011001050 >> 1Shift Right000110012550 << 1Shift Left01100100100I’ve included enough leading zeroes in the binary forms to make it easier to see the pattern of what’s happening.

      Bit shifting

    13. There are three standard logical bitwise operators:OperatorOperationDescription&Bitwise ANDThe result will have a bit set if both of the operands bits were set|Bitwise ORIf one or both of the operands have a bit set then the result will have that bit set^Bitwise XORIf one and only one of the operands (not both) has the bit set then the result will have the bit set.

      Bitwise

    14. Null Coalescing OperatorThe null coalescing operator is just a special case of the ternary operator. It allows you to neaten up the syntax used when you’re using isset to assign a default value to a variable.<?php// Long form ternary syntax$sortDirection = (isset($_GET['sort_dir'])) ? $_GET['sort_dir'] : 'ASC';// Equivalent syntax using the null coalescing operator$sortDirection = $_GET['sort_dir'] ?? 'ASC';// The null-coalesce operator can be chained$sortDirection = $_GET['sort_dir'] ?? $defaultSortDir ?? 'ASC';// The Elvis operator raises E_NOTICE if the GET variable is not set$sortDirection = $_GET['sort_dir'] ?: 'ASC'

      Null Coalescing Operator

    15. _LINE__The current line number of the PHP script being executed__FILE__The fully resolved (including symlinks) name and path of the file being executed__CLASS__The name of the class being executed__METHOD__The name of the class method being executed__FUNCTION__The name of the function being executed__TRAIT__The namespace and name of the trait that the code is running in__NAMESPACE__The current namespa

      Magical Constants

    16. LOBALSAn array of variables that exist in the global scope.$_SERVERAn array of information about paths, headers, and other information relevant to the server environment.$_GETVariables sent in a GET request.$_POSTVariables sent in a POST request.$_FILESAn associative array of files that were uploaded as part of a POSTrequest.$_COOKIEAn associative array of variables passed to the current script via HTTP cookies
    17. PHP variables begin with the dollar symbol $ and PHP variable names adhere to the following rules:• Names are case sensitive• Names may contain letters, numbers, and the underscore character• Names may not begin with a number