Javascript: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
|||
Line 1: | Line 1: | ||
=Javascript tips= | |||
== variables === | |||
Use let instead of var, let only works in scope | |||
Use const but remember arrays can be changed | |||
== functions === | |||
Assign function to variable | |||
<syntaxhighlight lang="javascript"> | |||
const X = () => { | |||
console.log("Fred"); | |||
} | |||
</syntaxhighlight> | |||
== destructure === | |||
<syntaxhighlight lang="javascript"> | |||
// const PI = Math.PI; | |||
// const E = Math.E; | |||
// const SQRT2 = Math.SQRT2; | |||
// Does the same | |||
const {PI, E, SQRT2} = Math; | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="javascript"> | |||
const circle = { | |||
label: 'circleX', | |||
radius: 2, | |||
}; | |||
const circleArea = {{radius}, {precision = 2} = {}) => | |||
(PI * radius * radius).toFixed(precision); | |||
console.log( | |||
circleArea(circle, {precision:5}) | |||
); | |||
</syntaxhighlight> | |||
=react functions and state= | =react functions and state= | ||
Revision as of 02:29, 19 May 2020
Javascript tips
variables =
Use let instead of var, let only works in scope Use const but remember arrays can be changed
functions =
Assign function to variable
const X = () => {
console.log("Fred");
}
destructure =
// const PI = Math.PI;
// const E = Math.E;
// const SQRT2 = Math.SQRT2;
// Does the same
const {PI, E, SQRT2} = Math;
const circle = {
label: 'circleX',
radius: 2,
};
const circleArea = {{radius}, {precision = 2} = {}) =>
(PI * radius * radius).toFixed(precision);
console.log(
circleArea(circle, {precision:5})
);
react functions and state
Normal function
function logRandom() {
console.log(Math.random());
}
function Button() {
const [count, setCounter] = useState(0);
return <button onClick={logRandom}>{counter}</button>;
}
inline function
function Button() {
const [count, setCounter] = useState(0);
return <button onClick={
function logRandom() {
console.log(Math.random());
}
}>{counter}</button>;
}
inline arrow function definition
function Button() {
const [count, setCounter] = useState(0);
return <button onClick={() = > console.log(Math.random())}>{counter}</button>;
}
Passing Props
function Button(props) {
const handleClick = () => props.onClickFunction(props.increment);
return (
<button onClick={handleClick}>
+{props.increment}
</button>
);
}
function Display(props) {
return (
<div>{props.message}</div>
);
}
function App() {
const [counter, setCounter] = useState(0);
const incrementCounter = (incrementValue) => setCounter(counter+incrementValue);
return (
<div>
<Button onClickFunction={incrementCounter} increment={1} />
<Button onClickFunction={incrementCounter} increment={5} />
<Button onClickFunction={incrementCounter} increment={10} />
<Button onClickFunction={incrementCounter} increment={100} />
<Display message={counter}/>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('mountNode'),
);