JS Reference

JS by Category JS by Alphabet

JavaScript

JS Array JS Boolean JS Classes JS Date JS Error JS Global JS JSON JS Math JS Number JS Operators JS RegExp JS Statements JS String

Window

Window Object Window Console Window History Window Location Window Navigator Window Screen

HTML DOM

DOM Document DOM Element DOM Attributes DOM Events DOM Event Objects DOM HTMLCollection DOM Style
alignContent alignItems alignSelf animation animationDelay animationDirection animationDuration animationFillMode animationIterationCount animationName animationTimingFunction animationPlayState background backgroundAttachment backgroundColor backgroundImage backgroundPosition backgroundRepeat backgroundClip backgroundOrigin backgroundSize backfaceVisibility border borderBottom borderBottomColor borderBottomLeftRadius borderBottomRightRadius borderBottomStyle borderBottomWidth borderCollapse borderColor borderImage borderImageOutset borderImageRepeat borderImageSlice borderImageSource borderImageWidth borderLeft borderLeftColor borderLeftStyle borderLeftWidth borderRadius borderRight borderRightColor borderRightStyle borderRightWidth borderSpacing borderStyle borderTop borderTopColor borderTopLeftRadius borderTopRightRadius borderTopStyle borderTopWidth borderWidth bottom boxShadow boxSizing captionSide caretColor clear clip color columnCount columnFill columnGap columnRule columnRuleColor columnRuleStyle columnRuleWidth columns columnSpan columnWidth counterIncrement counterReset cursor direction display emptyCells filter flex flexBasis flexDirection flexFlow flexGrow flexShrink flexWrap cssFloat font fontFamily fontSize fontStyle fontVariant fontWeight fontSizeAdjust height isolation justifyContent left letterSpacing lineHeight listStyle listStyleImage listStylePosition listStyleType margin marginBottom marginLeft marginRight marginTop maxHeight maxWidth minHeight minWidth objectFit objectPosition opacity order orphans outline outlineColor outlineOffset outlineStyle outlineWidth overflow overflowX overflowY padding paddingBottom paddingLeft paddingRight paddingTop pageBreakAfter pageBreakBefore pageBreakInside perspective perspectiveOrigin position quotes resize right scrollBehavior tableLayout tabSize textAlign textAlignLast textDecoration textDecorationColor textDecorationLine textDecorationStyle textIndent textOverflow textShadow textTransform top transform transformOrigin transformStyle transition transitionProperty transitionDuration transitionTimingFunction transitionDelay unicodeBidi userSelect verticalAlign visibility width wordBreak wordSpacing wordWrap widows zIndex

Web APIs

API Console API Fullscreen API Geolocation API History API MediaQueryList API Storage

HTML Objects

<a> <abbr> <address> <area> <article> <aside> <audio> <b> <base> <bdo> <blockquote> <body> <br> <button> <canvas> <caption> <cite> <code> <col> <colgroup> <datalist> <dd> <del> <details> <dfn> <dialog> <div> <dl> <dt> <em> <embed> <fieldset> <figcaption> <figure> <footer> <form> <head> <header> <h1> - <h6> <hr> <html> <i> <iframe> <img> <ins> <input> button <input> checkbox <input> color <input> date <input> datetime <input> datetime-local <input> email <input> file <input> hidden <input> image <input> month <input> number <input> password <input> radio <input> range <input> reset <input> search <input> submit <input> text <input> time <input> url <input> week <kbd> <label> <legend> <li> <link> <map> <mark> <menu> <menuitem> <meta> <meter> <nav> <object> <ol> <optgroup> <option> <output> <p> <param> <pre> <progress> <q> <s> <samp> <script> <section> <select> <small> <source> <span> <strong> <style> <sub> <summary> <sup> <table> <tbody> <td> <tfoot> <th> <thead> <tr> <textarea> <time> <title> <track> <u> <ul> <var> <video>

Other References

CSSStyleDeclaration JS Conversion


Referencia de operadores de JavaScript


Los operadores de JavaScript se utilizan para asignar valores, comparar valores, realizar operaciones aritméticas y más.


Operadores aritméticos de JavaScript

Los operadores aritméticos se utilizan para realizar operaciones aritméticas entre variables y/o valores.

Dado que y = 5 , la siguiente tabla explica los operadores aritméticos:

Operator Description Example Result in y Result in x Try it
+ Addition x = y + 2 y = 5 x = 7
- Subtraction x = y - 2 y = 5 x = 3
* Multiplication x = y * 2 y = 5 x = 10
/ Division x = y / 2 y = 5 x = 2.5
% Modulus (division remainder) x = y % 2 y = 5 x = 1
++ Increment x = ++y y = 6 x = 6
x = y++ y = 6 x = 5
-- Decrement x = --y y = 4 x = 4
x = y-- y = 4 x = 5

Para obtener un tutorial sobre operadores aritméticos, lea nuestro Tutorial de aritmética de JavaScript .


Operadores de asignación de JavaScript

Los operadores de asignación se utilizan para asignar valores a las variables de JavaScript.

Dado que x = 10 e y = 5 , la siguiente tabla explica los operadores de asignación:

Operator Example Same As Result in x Try it
= x = y x = y x = 5
+= x += y x = x + y x = 15
-= x -= y x = x - y x = 5
*= x *= y x = x * y x = 50
/= x /= y x = x / y x = 2
%= x %= y x = x % y x = 0

Para obtener un tutorial sobre los operadores de asignación, lea nuestro Tutorial de asignación de JavaScript .



Operadores de cadenas de JavaScript

El operador + y el operador += también se pueden usar para concatenar (agregar) cadenas.

Dado que text1 = "Bueno" , text2 = "Buenos días" y text3 = "" , la siguiente tabla explica los operadores:

Operator Example text1 text2 text3 Try it
+ text3 = text1 + text2 "Good " "Morning"  "Good Morning"
+= text1 += text2 "Good Morning" "Morning" ""

Operadores de comparación

Los operadores de comparación se utilizan en declaraciones lógicas para determinar la igualdad o diferencia entre variables o valores.

Dado que x = 5 , la siguiente tabla explica los operadores de comparación:

Operator Description Comparing Returns Try it
== equal to x == 8 false
x == 5 true
=== equal value and equal type x === "5" false
x === 5 true
!= not equal x != 8 true
!== not equal value or not equal type x !== "5" true
x !== 5 false
> greater than x > 8 false
< less than x < 8 true
>= greater than or equal to x >= 8 false
<= less than or equal to x <= 8 true

Para ver un tutorial sobre operadores de comparación, lea nuestro Tutorial de comparaciones de JavaScript .


Operador condicional (ternario)

El operador condicional asigna un valor a una variable en función de una condición.

Syntax Example Try it
variablename = (condition) ? value1:value2 voteable = (age < 18) ? "Too young":"Old enough";

Ejemplo explicado: Si la variable "edad" es un valor inferior a 18, el valor de la variable "votable" será "Demasiado joven", de lo contrario el valor de votable será "Suficientemente mayor".


Operadores logicos

Los operadores lógicos se utilizan para determinar la lógica entre variables o valores.

Dado que x = 6 e y = 3 , la siguiente tabla explica los operadores lógicos:

Operator Description Example Try it
&& and (x < 10 && y > 1) is true
|| or (x === 5 || y === 5) is false
! not !(x === y) is true

Operadores bit a bit de JavaScript

Los operadores de bits funcionan en números de 32 bits. Cualquier operando numérico en la operación se convierte en un número de 32 bits. El resultado se vuelve a convertir en un número de JavaScript.

Operator Description Example Same as Result Decimal
& AND x = 5 & 1 0101 & 0001 0001  1
| OR x = 5 | 1 0101 | 0001 0101  5
~ NOT x = ~ 5  ~0101 1010  10
^ XOR x = 5 ^ 1 0101 ^ 0001 0100  4
<< Left shift x = 5 << 1 0101 << 1 1010  10
>> Right shift x = 5 >> 1 0101 >> 1 0010   2

Los ejemplos anteriores usan ejemplos sin firmar de 4 bits. Pero JavaScript usa números con signo de 32 bits.

Debido a esto, en JavaScript, ~ 5 no devolverá 10. Devolverá -6.

~00000000000000000000000000000101 devolverá 111111111111111111111111111111010


El tipo de Operador

El operador typeof devuelve el tipo de una variable, objeto, función o expresión:

Ejemplo

typeof "John"                 // Returns string
typeof 3.14                   // Returns number
typeof NaN                    // Returns number
typeof false                  // Returns boolean
typeof [1, 2, 3, 4]           // Returns object
typeof {name:'John', age:34}  // Returns object
typeof new Date()             // Returns object
typeof function () {}         // Returns function
typeof myCar                  // Returns undefined (if myCar is not declared)
typeof null                   // Returns object

Por favor observe:

  • El tipo de datos de NaN es número
  • El tipo de datos de una matriz es objeto
  • El tipo de datos de una fecha es objeto.
  • El tipo de datos de nulo es objeto
  • El tipo de datos de una variable indefinida no está definido

No puede usar typeof para definir si un objeto de JavaScript es una matriz (o una fecha).


El operador de eliminación

El operador de eliminación elimina una propiedad de un objeto :

Ejemplo

const person = {
  firstName:"John",
  lastName:"Doe",
  age:50,
  eyeColor:"blue"
};
delete person.age;   // or delete person["age"];

El operador de eliminación elimina tanto el valor de la propiedad como la propiedad misma.

Después de la eliminación, la propiedad no se puede usar antes de que se vuelva a agregar.

El operador de eliminación está diseñado para usarse en propiedades de objetos. No tiene efecto sobre variables o funciones.

Nota: el operador de eliminación no debe usarse en propiedades de objeto de JavaScript predefinidas. Puede bloquear su aplicación.


El operador en

El operador in devuelve verdadero si la propiedad especificada está en el objeto especificado; de lo contrario, es falso:

Ejemplo

// Arrays
const cars = ["Saab", "Volvo", "BMW"];
"Saab" in cars          // Returns false (specify the index number instead of value)
0 in cars               // Returns true
1 in cars               // Returns true
4 in cars               // Returns false (does not exist)
"length" in cars        // Returns true  (length is an Array property)

// Objects
const person = {firstName:"John", lastName:"Doe", age:50};
"firstName" in person   // Returns true
"age" in person         // Returns true

// Predefined objects
"PI" in Math            // Returns true
"NaN" in Number         // Returns true
"length" in String      // Returns true

La instancia del Operador

El operador instanceof devuelve verdadero si el objeto especificado es una instancia del objeto especificado:

Ejemplo

const cars = ["Saab", "Volvo", "BMW"];

(cars instanceof Array)   // Returns true
(cars instanceof Object)  // Returns true
(cars instanceof String)  // Returns false
(cars instanceof Number)  // Returns false

El operador del vacío

El operador void evalúa una expresión y devuelve undefined . Este operador se usa a menudo para obtener el valor primitivo indefinido, usando "void(0)" (útil cuando se evalúa una expresión sin usar el valor devuelto).

Ejemplo

<a href="#;">
  Useless link
</a>

<a href="javascript:void(document.body.style.backgroundColor='red');">
  Click me to change the background color of body to red
</a>